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/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/MemoryLocation.h" 29 #include "llvm/Analysis/ProfileSummaryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineConstantPool.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 41 #include "llvm/CodeGen/SelectionDAGNodes.h" 42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 43 #include "llvm/CodeGen/TargetFrameLowering.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DebugLoc.h" 53 #include "llvm/IR/DerivedTypes.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/KnownBits.h" 65 #include "llvm/Support/MachineValueType.h" 66 #include "llvm/Support/ManagedStatic.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Mutex.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Target/TargetOptions.h" 72 #include "llvm/Transforms/Utils/SizeOpts.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <cstdlib> 77 #include <limits> 78 #include <set> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 /// makeVTList - Return an instance of the SDVTList struct initialized with the 86 /// specified members. 87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 88 SDVTList Res = {VTs, NumVTs}; 89 return Res; 90 } 91 92 // Default null implementations of the callbacks. 93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 96 97 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 98 99 #define DEBUG_TYPE "selectiondag" 100 101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 102 cl::Hidden, cl::init(true), 103 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 104 105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 106 cl::desc("Number limit for gluing ld/st of memcpy."), 107 cl::Hidden, cl::init(0)); 108 109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 110 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 111 } 112 113 //===----------------------------------------------------------------------===// 114 // ConstantFPSDNode Class 115 //===----------------------------------------------------------------------===// 116 117 /// isExactlyValue - We don't rely on operator== working on double values, as 118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 119 /// As such, this method can be used to do an exact bit-for-bit comparison of 120 /// two floating point values. 121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 122 return getValueAPF().bitwiseIsEqual(V); 123 } 124 125 bool ConstantFPSDNode::isValueValidForType(EVT VT, 126 const APFloat& Val) { 127 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 128 129 // convert modifies in place, so make a copy. 130 APFloat Val2 = APFloat(Val); 131 bool losesInfo; 132 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 133 APFloat::rmNearestTiesToEven, 134 &losesInfo); 135 return !losesInfo; 136 } 137 138 //===----------------------------------------------------------------------===// 139 // ISD Namespace 140 //===----------------------------------------------------------------------===// 141 142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 143 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 144 unsigned EltSize = 145 N->getValueType(0).getVectorElementType().getSizeInBits(); 146 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 147 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 148 return true; 149 } 150 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 151 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 152 return true; 153 } 154 } 155 156 auto *BV = dyn_cast<BuildVectorSDNode>(N); 157 if (!BV) 158 return false; 159 160 APInt SplatUndef; 161 unsigned SplatBitSize; 162 bool HasUndefs; 163 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 164 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 165 EltSize) && 166 EltSize == SplatBitSize; 167 } 168 169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 170 // specializations of the more general isConstantSplatVector()? 171 172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 173 // Look through a bit convert. 174 while (N->getOpcode() == ISD::BITCAST) 175 N = N->getOperand(0).getNode(); 176 177 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 178 APInt SplatVal; 179 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 180 } 181 182 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 183 184 unsigned i = 0, e = N->getNumOperands(); 185 186 // Skip over all of the undef values. 187 while (i != e && N->getOperand(i).isUndef()) 188 ++i; 189 190 // Do not accept an all-undef vector. 191 if (i == e) return false; 192 193 // Do not accept build_vectors that aren't all constants or which have non-~0 194 // elements. We have to be a bit careful here, as the type of the constant 195 // may not be the same as the type of the vector elements due to type 196 // legalization (the elements are promoted to a legal type for the target and 197 // a vector of a type may be legal when the base element type is not). 198 // We only want to check enough bits to cover the vector elements, because 199 // we care if the resultant vector is all ones, not whether the individual 200 // constants are. 201 SDValue NotZero = N->getOperand(i); 202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 204 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 205 return false; 206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 207 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 208 return false; 209 } else 210 return false; 211 212 // Okay, we have at least one ~0 value, check to see if the rest match or are 213 // undefs. Even with the above element type twiddling, this should be OK, as 214 // the same type legalization should have applied to all the elements. 215 for (++i; i != e; ++i) 216 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 217 return false; 218 return true; 219 } 220 221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 222 // Look through a bit convert. 223 while (N->getOpcode() == ISD::BITCAST) 224 N = N->getOperand(0).getNode(); 225 226 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 227 APInt SplatVal; 228 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 229 } 230 231 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 232 233 bool IsAllUndef = true; 234 for (const SDValue &Op : N->op_values()) { 235 if (Op.isUndef()) 236 continue; 237 IsAllUndef = false; 238 // Do not accept build_vectors that aren't all constants or which have non-0 239 // elements. We have to be a bit careful here, as the type of the constant 240 // may not be the same as the type of the vector elements due to type 241 // legalization (the elements are promoted to a legal type for the target 242 // and a vector of a type may be legal when the base element type is not). 243 // We only want to check enough bits to cover the vector elements, because 244 // we care if the resultant vector is all zeros, not whether the individual 245 // constants are. 246 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 248 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 249 return false; 250 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 251 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 252 return false; 253 } else 254 return false; 255 } 256 257 // Do not accept an all-undef vector. 258 if (IsAllUndef) 259 return false; 260 return true; 261 } 262 263 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 264 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 265 } 266 267 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 268 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 269 } 270 271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 272 if (N->getOpcode() != ISD::BUILD_VECTOR) 273 return false; 274 275 for (const SDValue &Op : N->op_values()) { 276 if (Op.isUndef()) 277 continue; 278 if (!isa<ConstantSDNode>(Op)) 279 return false; 280 } 281 return true; 282 } 283 284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 285 if (N->getOpcode() != ISD::BUILD_VECTOR) 286 return false; 287 288 for (const SDValue &Op : N->op_values()) { 289 if (Op.isUndef()) 290 continue; 291 if (!isa<ConstantFPSDNode>(Op)) 292 return false; 293 } 294 return true; 295 } 296 297 bool ISD::allOperandsUndef(const SDNode *N) { 298 // Return false if the node has no operands. 299 // This is "logically inconsistent" with the definition of "all" but 300 // is probably the desired behavior. 301 if (N->getNumOperands() == 0) 302 return false; 303 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 304 } 305 306 bool ISD::matchUnaryPredicate(SDValue Op, 307 std::function<bool(ConstantSDNode *)> Match, 308 bool AllowUndefs) { 309 // FIXME: Add support for scalar UNDEF cases? 310 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 311 return Match(Cst); 312 313 // FIXME: Add support for vector UNDEF cases? 314 if (ISD::BUILD_VECTOR != Op.getOpcode() && 315 ISD::SPLAT_VECTOR != Op.getOpcode()) 316 return false; 317 318 EVT SVT = Op.getValueType().getScalarType(); 319 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 320 if (AllowUndefs && Op.getOperand(i).isUndef()) { 321 if (!Match(nullptr)) 322 return false; 323 continue; 324 } 325 326 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 327 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 328 return false; 329 } 330 return true; 331 } 332 333 bool ISD::matchBinaryPredicate( 334 SDValue LHS, SDValue RHS, 335 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 336 bool AllowUndefs, bool AllowTypeMismatch) { 337 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 338 return false; 339 340 // TODO: Add support for scalar UNDEF cases? 341 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 342 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 343 return Match(LHSCst, RHSCst); 344 345 // TODO: Add support for vector UNDEF cases? 346 if (LHS.getOpcode() != RHS.getOpcode() || 347 (LHS.getOpcode() != ISD::BUILD_VECTOR && 348 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 349 return false; 350 351 EVT SVT = LHS.getValueType().getScalarType(); 352 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 353 SDValue LHSOp = LHS.getOperand(i); 354 SDValue RHSOp = RHS.getOperand(i); 355 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 356 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 357 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 358 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 359 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 360 return false; 361 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 362 LHSOp.getValueType() != RHSOp.getValueType())) 363 return false; 364 if (!Match(LHSCst, RHSCst)) 365 return false; 366 } 367 return true; 368 } 369 370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 371 switch (VecReduceOpcode) { 372 default: 373 llvm_unreachable("Expected VECREDUCE opcode"); 374 case ISD::VECREDUCE_FADD: 375 case ISD::VECREDUCE_SEQ_FADD: 376 return ISD::FADD; 377 case ISD::VECREDUCE_FMUL: 378 case ISD::VECREDUCE_SEQ_FMUL: 379 return ISD::FMUL; 380 case ISD::VECREDUCE_ADD: 381 return ISD::ADD; 382 case ISD::VECREDUCE_MUL: 383 return ISD::MUL; 384 case ISD::VECREDUCE_AND: 385 return ISD::AND; 386 case ISD::VECREDUCE_OR: 387 return ISD::OR; 388 case ISD::VECREDUCE_XOR: 389 return ISD::XOR; 390 case ISD::VECREDUCE_SMAX: 391 return ISD::SMAX; 392 case ISD::VECREDUCE_SMIN: 393 return ISD::SMIN; 394 case ISD::VECREDUCE_UMAX: 395 return ISD::UMAX; 396 case ISD::VECREDUCE_UMIN: 397 return ISD::UMIN; 398 case ISD::VECREDUCE_FMAX: 399 return ISD::FMAXNUM; 400 case ISD::VECREDUCE_FMIN: 401 return ISD::FMINNUM; 402 } 403 } 404 405 bool ISD::isVPOpcode(unsigned Opcode) { 406 switch (Opcode) { 407 default: 408 return false; 409 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 410 case ISD::VPSD: \ 411 return true; 412 #include "llvm/IR/VPIntrinsics.def" 413 } 414 } 415 416 bool ISD::isVPBinaryOp(unsigned Opcode) { 417 switch (Opcode) { 418 default: 419 break; 420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 421 #define VP_PROPERTY_BINARYOP return true; 422 #define END_REGISTER_VP_SDNODE(VPSD) break; 423 #include "llvm/IR/VPIntrinsics.def" 424 } 425 return false; 426 } 427 428 bool ISD::isVPReduction(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 /// The operand position of the vector mask. 441 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 442 switch (Opcode) { 443 default: 444 return None; 445 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 446 case ISD::VPSD: \ 447 return MASKPOS; 448 #include "llvm/IR/VPIntrinsics.def" 449 } 450 } 451 452 /// The operand position of the explicit vector length parameter. 453 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 458 case ISD::VPSD: \ 459 return EVLPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 465 switch (ExtType) { 466 case ISD::EXTLOAD: 467 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 468 case ISD::SEXTLOAD: 469 return ISD::SIGN_EXTEND; 470 case ISD::ZEXTLOAD: 471 return ISD::ZERO_EXTEND; 472 default: 473 break; 474 } 475 476 llvm_unreachable("Invalid LoadExtType"); 477 } 478 479 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 480 // To perform this operation, we just need to swap the L and G bits of the 481 // operation. 482 unsigned OldL = (Operation >> 2) & 1; 483 unsigned OldG = (Operation >> 1) & 1; 484 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 485 (OldL << 1) | // New G bit 486 (OldG << 2)); // New L bit. 487 } 488 489 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 490 unsigned Operation = Op; 491 if (isIntegerLike) 492 Operation ^= 7; // Flip L, G, E bits, but not U. 493 else 494 Operation ^= 15; // Flip all of the condition bits. 495 496 if (Operation > ISD::SETTRUE2) 497 Operation &= ~8; // Don't let N and U bits get set. 498 499 return ISD::CondCode(Operation); 500 } 501 502 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 503 return getSetCCInverseImpl(Op, Type.isInteger()); 504 } 505 506 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 507 bool isIntegerLike) { 508 return getSetCCInverseImpl(Op, isIntegerLike); 509 } 510 511 /// For an integer comparison, return 1 if the comparison is a signed operation 512 /// and 2 if the result is an unsigned comparison. Return zero if the operation 513 /// does not depend on the sign of the input (setne and seteq). 514 static int isSignedOp(ISD::CondCode Opcode) { 515 switch (Opcode) { 516 default: llvm_unreachable("Illegal integer setcc operation!"); 517 case ISD::SETEQ: 518 case ISD::SETNE: return 0; 519 case ISD::SETLT: 520 case ISD::SETLE: 521 case ISD::SETGT: 522 case ISD::SETGE: return 1; 523 case ISD::SETULT: 524 case ISD::SETULE: 525 case ISD::SETUGT: 526 case ISD::SETUGE: return 2; 527 } 528 } 529 530 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 531 EVT Type) { 532 bool IsInteger = Type.isInteger(); 533 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 534 // Cannot fold a signed integer setcc with an unsigned integer setcc. 535 return ISD::SETCC_INVALID; 536 537 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 538 539 // If the N and U bits get set, then the resultant comparison DOES suddenly 540 // care about orderedness, and it is true when ordered. 541 if (Op > ISD::SETTRUE2) 542 Op &= ~16; // Clear the U bit if the N bit is set. 543 544 // Canonicalize illegal integer setcc's. 545 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 546 Op = ISD::SETNE; 547 548 return ISD::CondCode(Op); 549 } 550 551 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 552 EVT Type) { 553 bool IsInteger = Type.isInteger(); 554 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 555 // Cannot fold a signed setcc with an unsigned setcc. 556 return ISD::SETCC_INVALID; 557 558 // Combine all of the condition bits. 559 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 560 561 // Canonicalize illegal integer setcc's. 562 if (IsInteger) { 563 switch (Result) { 564 default: break; 565 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 566 case ISD::SETOEQ: // SETEQ & SETU[LG]E 567 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 568 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 569 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 570 } 571 } 572 573 return Result; 574 } 575 576 //===----------------------------------------------------------------------===// 577 // SDNode Profile Support 578 //===----------------------------------------------------------------------===// 579 580 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 581 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 582 ID.AddInteger(OpC); 583 } 584 585 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 586 /// solely with their pointer. 587 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 588 ID.AddPointer(VTList.VTs); 589 } 590 591 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 592 static void AddNodeIDOperands(FoldingSetNodeID &ID, 593 ArrayRef<SDValue> Ops) { 594 for (auto& Op : Ops) { 595 ID.AddPointer(Op.getNode()); 596 ID.AddInteger(Op.getResNo()); 597 } 598 } 599 600 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 601 static void AddNodeIDOperands(FoldingSetNodeID &ID, 602 ArrayRef<SDUse> Ops) { 603 for (auto& Op : Ops) { 604 ID.AddPointer(Op.getNode()); 605 ID.AddInteger(Op.getResNo()); 606 } 607 } 608 609 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 610 SDVTList VTList, ArrayRef<SDValue> OpList) { 611 AddNodeIDOpcode(ID, OpC); 612 AddNodeIDValueTypes(ID, VTList); 613 AddNodeIDOperands(ID, OpList); 614 } 615 616 /// If this is an SDNode with special info, add this info to the NodeID data. 617 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 618 switch (N->getOpcode()) { 619 case ISD::TargetExternalSymbol: 620 case ISD::ExternalSymbol: 621 case ISD::MCSymbol: 622 llvm_unreachable("Should only be used on nodes with operands"); 623 default: break; // Normal nodes don't need extra info. 624 case ISD::TargetConstant: 625 case ISD::Constant: { 626 const ConstantSDNode *C = cast<ConstantSDNode>(N); 627 ID.AddPointer(C->getConstantIntValue()); 628 ID.AddBoolean(C->isOpaque()); 629 break; 630 } 631 case ISD::TargetConstantFP: 632 case ISD::ConstantFP: 633 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 634 break; 635 case ISD::TargetGlobalAddress: 636 case ISD::GlobalAddress: 637 case ISD::TargetGlobalTLSAddress: 638 case ISD::GlobalTLSAddress: { 639 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 640 ID.AddPointer(GA->getGlobal()); 641 ID.AddInteger(GA->getOffset()); 642 ID.AddInteger(GA->getTargetFlags()); 643 break; 644 } 645 case ISD::BasicBlock: 646 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 647 break; 648 case ISD::Register: 649 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 650 break; 651 case ISD::RegisterMask: 652 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 653 break; 654 case ISD::SRCVALUE: 655 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 656 break; 657 case ISD::FrameIndex: 658 case ISD::TargetFrameIndex: 659 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 660 break; 661 case ISD::LIFETIME_START: 662 case ISD::LIFETIME_END: 663 if (cast<LifetimeSDNode>(N)->hasOffset()) { 664 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 665 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 666 } 667 break; 668 case ISD::PSEUDO_PROBE: 669 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 670 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 671 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 672 break; 673 case ISD::JumpTable: 674 case ISD::TargetJumpTable: 675 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 676 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 677 break; 678 case ISD::ConstantPool: 679 case ISD::TargetConstantPool: { 680 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 681 ID.AddInteger(CP->getAlign().value()); 682 ID.AddInteger(CP->getOffset()); 683 if (CP->isMachineConstantPoolEntry()) 684 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 685 else 686 ID.AddPointer(CP->getConstVal()); 687 ID.AddInteger(CP->getTargetFlags()); 688 break; 689 } 690 case ISD::TargetIndex: { 691 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 692 ID.AddInteger(TI->getIndex()); 693 ID.AddInteger(TI->getOffset()); 694 ID.AddInteger(TI->getTargetFlags()); 695 break; 696 } 697 case ISD::LOAD: { 698 const LoadSDNode *LD = cast<LoadSDNode>(N); 699 ID.AddInteger(LD->getMemoryVT().getRawBits()); 700 ID.AddInteger(LD->getRawSubclassData()); 701 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 702 break; 703 } 704 case ISD::STORE: { 705 const StoreSDNode *ST = cast<StoreSDNode>(N); 706 ID.AddInteger(ST->getMemoryVT().getRawBits()); 707 ID.AddInteger(ST->getRawSubclassData()); 708 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 709 break; 710 } 711 case ISD::VP_LOAD: { 712 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 713 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 714 ID.AddInteger(ELD->getRawSubclassData()); 715 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 716 break; 717 } 718 case ISD::VP_STORE: { 719 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 720 ID.AddInteger(EST->getMemoryVT().getRawBits()); 721 ID.AddInteger(EST->getRawSubclassData()); 722 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 723 break; 724 } 725 case ISD::VP_GATHER: { 726 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 727 ID.AddInteger(EG->getMemoryVT().getRawBits()); 728 ID.AddInteger(EG->getRawSubclassData()); 729 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 730 break; 731 } 732 case ISD::VP_SCATTER: { 733 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 734 ID.AddInteger(ES->getMemoryVT().getRawBits()); 735 ID.AddInteger(ES->getRawSubclassData()); 736 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 737 break; 738 } 739 case ISD::MLOAD: { 740 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 741 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 742 ID.AddInteger(MLD->getRawSubclassData()); 743 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 744 break; 745 } 746 case ISD::MSTORE: { 747 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 748 ID.AddInteger(MST->getMemoryVT().getRawBits()); 749 ID.AddInteger(MST->getRawSubclassData()); 750 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 751 break; 752 } 753 case ISD::MGATHER: { 754 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 755 ID.AddInteger(MG->getMemoryVT().getRawBits()); 756 ID.AddInteger(MG->getRawSubclassData()); 757 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 758 break; 759 } 760 case ISD::MSCATTER: { 761 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 762 ID.AddInteger(MS->getMemoryVT().getRawBits()); 763 ID.AddInteger(MS->getRawSubclassData()); 764 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 765 break; 766 } 767 case ISD::ATOMIC_CMP_SWAP: 768 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 769 case ISD::ATOMIC_SWAP: 770 case ISD::ATOMIC_LOAD_ADD: 771 case ISD::ATOMIC_LOAD_SUB: 772 case ISD::ATOMIC_LOAD_AND: 773 case ISD::ATOMIC_LOAD_CLR: 774 case ISD::ATOMIC_LOAD_OR: 775 case ISD::ATOMIC_LOAD_XOR: 776 case ISD::ATOMIC_LOAD_NAND: 777 case ISD::ATOMIC_LOAD_MIN: 778 case ISD::ATOMIC_LOAD_MAX: 779 case ISD::ATOMIC_LOAD_UMIN: 780 case ISD::ATOMIC_LOAD_UMAX: 781 case ISD::ATOMIC_LOAD: 782 case ISD::ATOMIC_STORE: { 783 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 784 ID.AddInteger(AT->getMemoryVT().getRawBits()); 785 ID.AddInteger(AT->getRawSubclassData()); 786 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 787 break; 788 } 789 case ISD::PREFETCH: { 790 const MemSDNode *PF = cast<MemSDNode>(N); 791 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 792 break; 793 } 794 case ISD::VECTOR_SHUFFLE: { 795 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 796 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 797 i != e; ++i) 798 ID.AddInteger(SVN->getMaskElt(i)); 799 break; 800 } 801 case ISD::TargetBlockAddress: 802 case ISD::BlockAddress: { 803 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 804 ID.AddPointer(BA->getBlockAddress()); 805 ID.AddInteger(BA->getOffset()); 806 ID.AddInteger(BA->getTargetFlags()); 807 break; 808 } 809 } // end switch (N->getOpcode()) 810 811 // Target specific memory nodes could also have address spaces to check. 812 if (N->isTargetMemoryOpcode()) 813 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 814 } 815 816 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 817 /// data. 818 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 819 AddNodeIDOpcode(ID, N->getOpcode()); 820 // Add the return value info. 821 AddNodeIDValueTypes(ID, N->getVTList()); 822 // Add the operand info. 823 AddNodeIDOperands(ID, N->ops()); 824 825 // Handle SDNode leafs with special info. 826 AddNodeIDCustom(ID, N); 827 } 828 829 //===----------------------------------------------------------------------===// 830 // SelectionDAG Class 831 //===----------------------------------------------------------------------===// 832 833 /// doNotCSE - Return true if CSE should not be performed for this node. 834 static bool doNotCSE(SDNode *N) { 835 if (N->getValueType(0) == MVT::Glue) 836 return true; // Never CSE anything that produces a flag. 837 838 switch (N->getOpcode()) { 839 default: break; 840 case ISD::HANDLENODE: 841 case ISD::EH_LABEL: 842 return true; // Never CSE these nodes. 843 } 844 845 // Check that remaining values produced are not flags. 846 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 847 if (N->getValueType(i) == MVT::Glue) 848 return true; // Never CSE anything that produces a flag. 849 850 return false; 851 } 852 853 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 854 /// SelectionDAG. 855 void SelectionDAG::RemoveDeadNodes() { 856 // Create a dummy node (which is not added to allnodes), that adds a reference 857 // to the root node, preventing it from being deleted. 858 HandleSDNode Dummy(getRoot()); 859 860 SmallVector<SDNode*, 128> DeadNodes; 861 862 // Add all obviously-dead nodes to the DeadNodes worklist. 863 for (SDNode &Node : allnodes()) 864 if (Node.use_empty()) 865 DeadNodes.push_back(&Node); 866 867 RemoveDeadNodes(DeadNodes); 868 869 // If the root changed (e.g. it was a dead load, update the root). 870 setRoot(Dummy.getValue()); 871 } 872 873 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 874 /// given list, and any nodes that become unreachable as a result. 875 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 876 877 // Process the worklist, deleting the nodes and adding their uses to the 878 // worklist. 879 while (!DeadNodes.empty()) { 880 SDNode *N = DeadNodes.pop_back_val(); 881 // Skip to next node if we've already managed to delete the node. This could 882 // happen if replacing a node causes a node previously added to the node to 883 // be deleted. 884 if (N->getOpcode() == ISD::DELETED_NODE) 885 continue; 886 887 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 888 DUL->NodeDeleted(N, nullptr); 889 890 // Take the node out of the appropriate CSE map. 891 RemoveNodeFromCSEMaps(N); 892 893 // Next, brutally remove the operand list. This is safe to do, as there are 894 // no cycles in the graph. 895 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 896 SDUse &Use = *I++; 897 SDNode *Operand = Use.getNode(); 898 Use.set(SDValue()); 899 900 // Now that we removed this operand, see if there are no uses of it left. 901 if (Operand->use_empty()) 902 DeadNodes.push_back(Operand); 903 } 904 905 DeallocateNode(N); 906 } 907 } 908 909 void SelectionDAG::RemoveDeadNode(SDNode *N){ 910 SmallVector<SDNode*, 16> DeadNodes(1, N); 911 912 // Create a dummy node that adds a reference to the root node, preventing 913 // it from being deleted. (This matters if the root is an operand of the 914 // dead node.) 915 HandleSDNode Dummy(getRoot()); 916 917 RemoveDeadNodes(DeadNodes); 918 } 919 920 void SelectionDAG::DeleteNode(SDNode *N) { 921 // First take this out of the appropriate CSE map. 922 RemoveNodeFromCSEMaps(N); 923 924 // Finally, remove uses due to operands of this node, remove from the 925 // AllNodes list, and delete the node. 926 DeleteNodeNotInCSEMaps(N); 927 } 928 929 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 930 assert(N->getIterator() != AllNodes.begin() && 931 "Cannot delete the entry node!"); 932 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 933 934 // Drop all of the operands and decrement used node's use counts. 935 N->DropOperands(); 936 937 DeallocateNode(N); 938 } 939 940 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 941 assert(!(V->isVariadic() && isParameter)); 942 if (isParameter) 943 ByvalParmDbgValues.push_back(V); 944 else 945 DbgValues.push_back(V); 946 for (const SDNode *Node : V->getSDNodes()) 947 if (Node) 948 DbgValMap[Node].push_back(V); 949 } 950 951 void SDDbgInfo::erase(const SDNode *Node) { 952 DbgValMapType::iterator I = DbgValMap.find(Node); 953 if (I == DbgValMap.end()) 954 return; 955 for (auto &Val: I->second) 956 Val->setIsInvalidated(); 957 DbgValMap.erase(I); 958 } 959 960 void SelectionDAG::DeallocateNode(SDNode *N) { 961 // If we have operands, deallocate them. 962 removeOperands(N); 963 964 NodeAllocator.Deallocate(AllNodes.remove(N)); 965 966 // Set the opcode to DELETED_NODE to help catch bugs when node 967 // memory is reallocated. 968 // FIXME: There are places in SDag that have grown a dependency on the opcode 969 // value in the released node. 970 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 971 N->NodeType = ISD::DELETED_NODE; 972 973 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 974 // them and forget about that node. 975 DbgInfo->erase(N); 976 } 977 978 #ifndef NDEBUG 979 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 980 static void VerifySDNode(SDNode *N) { 981 switch (N->getOpcode()) { 982 default: 983 break; 984 case ISD::BUILD_PAIR: { 985 EVT VT = N->getValueType(0); 986 assert(N->getNumValues() == 1 && "Too many results!"); 987 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 988 "Wrong return type!"); 989 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 990 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 991 "Mismatched operand types!"); 992 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 993 "Wrong operand type!"); 994 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 995 "Wrong return type size"); 996 break; 997 } 998 case ISD::BUILD_VECTOR: { 999 assert(N->getNumValues() == 1 && "Too many results!"); 1000 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1001 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1002 "Wrong number of operands!"); 1003 EVT EltVT = N->getValueType(0).getVectorElementType(); 1004 for (const SDUse &Op : N->ops()) { 1005 assert((Op.getValueType() == EltVT || 1006 (EltVT.isInteger() && Op.getValueType().isInteger() && 1007 EltVT.bitsLE(Op.getValueType()))) && 1008 "Wrong operand type!"); 1009 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1010 "Operands must all have the same type"); 1011 } 1012 break; 1013 } 1014 } 1015 } 1016 #endif // NDEBUG 1017 1018 /// Insert a newly allocated node into the DAG. 1019 /// 1020 /// Handles insertion into the all nodes list and CSE map, as well as 1021 /// verification and other common operations when a new node is allocated. 1022 void SelectionDAG::InsertNode(SDNode *N) { 1023 AllNodes.push_back(N); 1024 #ifndef NDEBUG 1025 N->PersistentId = NextPersistentId++; 1026 VerifySDNode(N); 1027 #endif 1028 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1029 DUL->NodeInserted(N); 1030 } 1031 1032 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1033 /// correspond to it. This is useful when we're about to delete or repurpose 1034 /// the node. We don't want future request for structurally identical nodes 1035 /// to return N anymore. 1036 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1037 bool Erased = false; 1038 switch (N->getOpcode()) { 1039 case ISD::HANDLENODE: return false; // noop. 1040 case ISD::CONDCODE: 1041 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1042 "Cond code doesn't exist!"); 1043 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1044 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1045 break; 1046 case ISD::ExternalSymbol: 1047 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1048 break; 1049 case ISD::TargetExternalSymbol: { 1050 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1051 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1052 ESN->getSymbol(), ESN->getTargetFlags())); 1053 break; 1054 } 1055 case ISD::MCSymbol: { 1056 auto *MCSN = cast<MCSymbolSDNode>(N); 1057 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1058 break; 1059 } 1060 case ISD::VALUETYPE: { 1061 EVT VT = cast<VTSDNode>(N)->getVT(); 1062 if (VT.isExtended()) { 1063 Erased = ExtendedValueTypeNodes.erase(VT); 1064 } else { 1065 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1066 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1067 } 1068 break; 1069 } 1070 default: 1071 // Remove it from the CSE Map. 1072 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1073 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1074 Erased = CSEMap.RemoveNode(N); 1075 break; 1076 } 1077 #ifndef NDEBUG 1078 // Verify that the node was actually in one of the CSE maps, unless it has a 1079 // flag result (which cannot be CSE'd) or is one of the special cases that are 1080 // not subject to CSE. 1081 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1082 !N->isMachineOpcode() && !doNotCSE(N)) { 1083 N->dump(this); 1084 dbgs() << "\n"; 1085 llvm_unreachable("Node is not in map!"); 1086 } 1087 #endif 1088 return Erased; 1089 } 1090 1091 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1092 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1093 /// node already exists, in which case transfer all its users to the existing 1094 /// node. This transfer can potentially trigger recursive merging. 1095 void 1096 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1097 // For node types that aren't CSE'd, just act as if no identical node 1098 // already exists. 1099 if (!doNotCSE(N)) { 1100 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1101 if (Existing != N) { 1102 // If there was already an existing matching node, use ReplaceAllUsesWith 1103 // to replace the dead one with the existing one. This can cause 1104 // recursive merging of other unrelated nodes down the line. 1105 ReplaceAllUsesWith(N, Existing); 1106 1107 // N is now dead. Inform the listeners and delete it. 1108 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1109 DUL->NodeDeleted(N, Existing); 1110 DeleteNodeNotInCSEMaps(N); 1111 return; 1112 } 1113 } 1114 1115 // If the node doesn't already exist, we updated it. Inform listeners. 1116 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1117 DUL->NodeUpdated(N); 1118 } 1119 1120 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1121 /// were replaced with those specified. If this node is never memoized, 1122 /// return null, otherwise return a pointer to the slot it would take. If a 1123 /// node already exists with these operands, the slot will be non-null. 1124 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1125 void *&InsertPos) { 1126 if (doNotCSE(N)) 1127 return nullptr; 1128 1129 SDValue Ops[] = { Op }; 1130 FoldingSetNodeID ID; 1131 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1132 AddNodeIDCustom(ID, N); 1133 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1134 if (Node) 1135 Node->intersectFlagsWith(N->getFlags()); 1136 return Node; 1137 } 1138 1139 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1140 /// were replaced with those specified. If this node is never memoized, 1141 /// return null, otherwise return a pointer to the slot it would take. If a 1142 /// node already exists with these operands, the slot will be non-null. 1143 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1144 SDValue Op1, SDValue Op2, 1145 void *&InsertPos) { 1146 if (doNotCSE(N)) 1147 return nullptr; 1148 1149 SDValue Ops[] = { Op1, Op2 }; 1150 FoldingSetNodeID ID; 1151 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1152 AddNodeIDCustom(ID, N); 1153 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1154 if (Node) 1155 Node->intersectFlagsWith(N->getFlags()); 1156 return Node; 1157 } 1158 1159 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1160 /// were replaced with those specified. If this node is never memoized, 1161 /// return null, otherwise return a pointer to the slot it would take. If a 1162 /// node already exists with these operands, the slot will be non-null. 1163 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1164 void *&InsertPos) { 1165 if (doNotCSE(N)) 1166 return nullptr; 1167 1168 FoldingSetNodeID ID; 1169 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1170 AddNodeIDCustom(ID, N); 1171 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1172 if (Node) 1173 Node->intersectFlagsWith(N->getFlags()); 1174 return Node; 1175 } 1176 1177 Align SelectionDAG::getEVTAlign(EVT VT) const { 1178 Type *Ty = VT == MVT::iPTR ? 1179 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1180 VT.getTypeForEVT(*getContext()); 1181 1182 return getDataLayout().getABITypeAlign(Ty); 1183 } 1184 1185 // EntryNode could meaningfully have debug info if we can find it... 1186 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1187 : TM(tm), OptLevel(OL), 1188 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1189 Root(getEntryNode()) { 1190 InsertNode(&EntryNode); 1191 DbgInfo = new SDDbgInfo(); 1192 } 1193 1194 void SelectionDAG::init(MachineFunction &NewMF, 1195 OptimizationRemarkEmitter &NewORE, 1196 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1197 LegacyDivergenceAnalysis * Divergence, 1198 ProfileSummaryInfo *PSIin, 1199 BlockFrequencyInfo *BFIin) { 1200 MF = &NewMF; 1201 SDAGISelPass = PassPtr; 1202 ORE = &NewORE; 1203 TLI = getSubtarget().getTargetLowering(); 1204 TSI = getSubtarget().getSelectionDAGInfo(); 1205 LibInfo = LibraryInfo; 1206 Context = &MF->getFunction().getContext(); 1207 DA = Divergence; 1208 PSI = PSIin; 1209 BFI = BFIin; 1210 } 1211 1212 SelectionDAG::~SelectionDAG() { 1213 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1214 allnodes_clear(); 1215 OperandRecycler.clear(OperandAllocator); 1216 delete DbgInfo; 1217 } 1218 1219 bool SelectionDAG::shouldOptForSize() const { 1220 return MF->getFunction().hasOptSize() || 1221 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1222 } 1223 1224 void SelectionDAG::allnodes_clear() { 1225 assert(&*AllNodes.begin() == &EntryNode); 1226 AllNodes.remove(AllNodes.begin()); 1227 while (!AllNodes.empty()) 1228 DeallocateNode(&AllNodes.front()); 1229 #ifndef NDEBUG 1230 NextPersistentId = 0; 1231 #endif 1232 } 1233 1234 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1235 void *&InsertPos) { 1236 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1237 if (N) { 1238 switch (N->getOpcode()) { 1239 default: break; 1240 case ISD::Constant: 1241 case ISD::ConstantFP: 1242 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1243 "debug location. Use another overload."); 1244 } 1245 } 1246 return N; 1247 } 1248 1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1250 const SDLoc &DL, void *&InsertPos) { 1251 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1252 if (N) { 1253 switch (N->getOpcode()) { 1254 case ISD::Constant: 1255 case ISD::ConstantFP: 1256 // Erase debug location from the node if the node is used at several 1257 // different places. Do not propagate one location to all uses as it 1258 // will cause a worse single stepping debugging experience. 1259 if (N->getDebugLoc() != DL.getDebugLoc()) 1260 N->setDebugLoc(DebugLoc()); 1261 break; 1262 default: 1263 // When the node's point of use is located earlier in the instruction 1264 // sequence than its prior point of use, update its debug info to the 1265 // earlier location. 1266 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1267 N->setDebugLoc(DL.getDebugLoc()); 1268 break; 1269 } 1270 } 1271 return N; 1272 } 1273 1274 void SelectionDAG::clear() { 1275 allnodes_clear(); 1276 OperandRecycler.clear(OperandAllocator); 1277 OperandAllocator.Reset(); 1278 CSEMap.clear(); 1279 1280 ExtendedValueTypeNodes.clear(); 1281 ExternalSymbols.clear(); 1282 TargetExternalSymbols.clear(); 1283 MCSymbols.clear(); 1284 SDCallSiteDbgInfo.clear(); 1285 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1286 static_cast<CondCodeSDNode*>(nullptr)); 1287 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1288 static_cast<SDNode*>(nullptr)); 1289 1290 EntryNode.UseList = nullptr; 1291 InsertNode(&EntryNode); 1292 Root = getEntryNode(); 1293 DbgInfo->clear(); 1294 } 1295 1296 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1297 return VT.bitsGT(Op.getValueType()) 1298 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1299 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1300 } 1301 1302 std::pair<SDValue, SDValue> 1303 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1304 const SDLoc &DL, EVT VT) { 1305 assert(!VT.bitsEq(Op.getValueType()) && 1306 "Strict no-op FP extend/round not allowed."); 1307 SDValue Res = 1308 VT.bitsGT(Op.getValueType()) 1309 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1310 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1311 {Chain, Op, getIntPtrConstant(0, DL)}); 1312 1313 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1314 } 1315 1316 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1317 return VT.bitsGT(Op.getValueType()) ? 1318 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1319 getNode(ISD::TRUNCATE, DL, VT, Op); 1320 } 1321 1322 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1323 return VT.bitsGT(Op.getValueType()) ? 1324 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1325 getNode(ISD::TRUNCATE, DL, VT, Op); 1326 } 1327 1328 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1329 return VT.bitsGT(Op.getValueType()) ? 1330 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1331 getNode(ISD::TRUNCATE, DL, VT, Op); 1332 } 1333 1334 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1335 EVT OpVT) { 1336 if (VT.bitsLE(Op.getValueType())) 1337 return getNode(ISD::TRUNCATE, SL, VT, Op); 1338 1339 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1340 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1341 } 1342 1343 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1344 EVT OpVT = Op.getValueType(); 1345 assert(VT.isInteger() && OpVT.isInteger() && 1346 "Cannot getZeroExtendInReg FP types"); 1347 assert(VT.isVector() == OpVT.isVector() && 1348 "getZeroExtendInReg type should be vector iff the operand " 1349 "type is vector!"); 1350 assert((!VT.isVector() || 1351 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1352 "Vector element counts must match in getZeroExtendInReg"); 1353 assert(VT.bitsLE(OpVT) && "Not extending!"); 1354 if (OpVT == VT) 1355 return Op; 1356 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1357 VT.getScalarSizeInBits()); 1358 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1359 } 1360 1361 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 // Only unsigned pointer semantics are supported right now. In the future this 1363 // might delegate to TLI to check pointer signedness. 1364 return getZExtOrTrunc(Op, DL, VT); 1365 } 1366 1367 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1368 // Only unsigned pointer semantics are supported right now. In the future this 1369 // might delegate to TLI to check pointer signedness. 1370 return getZeroExtendInReg(Op, DL, VT); 1371 } 1372 1373 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1374 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1375 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1376 } 1377 1378 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1379 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1380 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1381 } 1382 1383 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1384 EVT OpVT) { 1385 if (!V) 1386 return getConstant(0, DL, VT); 1387 1388 switch (TLI->getBooleanContents(OpVT)) { 1389 case TargetLowering::ZeroOrOneBooleanContent: 1390 case TargetLowering::UndefinedBooleanContent: 1391 return getConstant(1, DL, VT); 1392 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1393 return getAllOnesConstant(DL, VT); 1394 } 1395 llvm_unreachable("Unexpected boolean content enum!"); 1396 } 1397 1398 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1399 bool isT, bool isO) { 1400 EVT EltVT = VT.getScalarType(); 1401 assert((EltVT.getSizeInBits() >= 64 || 1402 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1403 "getConstant with a uint64_t value that doesn't fit in the type!"); 1404 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1405 } 1406 1407 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1408 bool isT, bool isO) { 1409 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1410 } 1411 1412 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1413 EVT VT, bool isT, bool isO) { 1414 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1415 1416 EVT EltVT = VT.getScalarType(); 1417 const ConstantInt *Elt = &Val; 1418 1419 // In some cases the vector type is legal but the element type is illegal and 1420 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1421 // inserted value (the type does not need to match the vector element type). 1422 // Any extra bits introduced will be truncated away. 1423 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1424 TargetLowering::TypePromoteInteger) { 1425 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1426 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1427 Elt = ConstantInt::get(*getContext(), NewVal); 1428 } 1429 // In other cases the element type is illegal and needs to be expanded, for 1430 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1431 // the value into n parts and use a vector type with n-times the elements. 1432 // Then bitcast to the type requested. 1433 // Legalizing constants too early makes the DAGCombiner's job harder so we 1434 // only legalize if the DAG tells us we must produce legal types. 1435 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1436 TLI->getTypeAction(*getContext(), EltVT) == 1437 TargetLowering::TypeExpandInteger) { 1438 const APInt &NewVal = Elt->getValue(); 1439 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1440 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1441 1442 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1443 if (VT.isScalableVector()) { 1444 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1445 "Can only handle an even split!"); 1446 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1447 1448 SmallVector<SDValue, 2> ScalarParts; 1449 for (unsigned i = 0; i != Parts; ++i) 1450 ScalarParts.push_back(getConstant( 1451 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1452 ViaEltVT, isT, isO)); 1453 1454 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1455 } 1456 1457 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1458 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1459 1460 // Check the temporary vector is the correct size. If this fails then 1461 // getTypeToTransformTo() probably returned a type whose size (in bits) 1462 // isn't a power-of-2 factor of the requested type size. 1463 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1464 1465 SmallVector<SDValue, 2> EltParts; 1466 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1467 EltParts.push_back(getConstant( 1468 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1469 ViaEltVT, isT, isO)); 1470 1471 // EltParts is currently in little endian order. If we actually want 1472 // big-endian order then reverse it now. 1473 if (getDataLayout().isBigEndian()) 1474 std::reverse(EltParts.begin(), EltParts.end()); 1475 1476 // The elements must be reversed when the element order is different 1477 // to the endianness of the elements (because the BITCAST is itself a 1478 // vector shuffle in this situation). However, we do not need any code to 1479 // perform this reversal because getConstant() is producing a vector 1480 // splat. 1481 // This situation occurs in MIPS MSA. 1482 1483 SmallVector<SDValue, 8> Ops; 1484 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1485 llvm::append_range(Ops, EltParts); 1486 1487 SDValue V = 1488 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1489 return V; 1490 } 1491 1492 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1493 "APInt size does not match type size!"); 1494 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1495 FoldingSetNodeID ID; 1496 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1497 ID.AddPointer(Elt); 1498 ID.AddBoolean(isO); 1499 void *IP = nullptr; 1500 SDNode *N = nullptr; 1501 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1502 if (!VT.isVector()) 1503 return SDValue(N, 0); 1504 1505 if (!N) { 1506 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1507 CSEMap.InsertNode(N, IP); 1508 InsertNode(N); 1509 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1510 } 1511 1512 SDValue Result(N, 0); 1513 if (VT.isScalableVector()) 1514 Result = getSplatVector(VT, DL, Result); 1515 else if (VT.isVector()) 1516 Result = getSplatBuildVector(VT, DL, Result); 1517 1518 return Result; 1519 } 1520 1521 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1522 bool isTarget) { 1523 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1524 } 1525 1526 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1527 const SDLoc &DL, bool LegalTypes) { 1528 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1529 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1530 return getConstant(Val, DL, ShiftVT); 1531 } 1532 1533 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1534 bool isTarget) { 1535 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1536 } 1537 1538 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1539 bool isTarget) { 1540 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1541 } 1542 1543 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1544 EVT VT, bool isTarget) { 1545 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1546 1547 EVT EltVT = VT.getScalarType(); 1548 1549 // Do the map lookup using the actual bit pattern for the floating point 1550 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1551 // we don't have issues with SNANs. 1552 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1553 FoldingSetNodeID ID; 1554 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1555 ID.AddPointer(&V); 1556 void *IP = nullptr; 1557 SDNode *N = nullptr; 1558 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1559 if (!VT.isVector()) 1560 return SDValue(N, 0); 1561 1562 if (!N) { 1563 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1564 CSEMap.InsertNode(N, IP); 1565 InsertNode(N); 1566 } 1567 1568 SDValue Result(N, 0); 1569 if (VT.isScalableVector()) 1570 Result = getSplatVector(VT, DL, Result); 1571 else if (VT.isVector()) 1572 Result = getSplatBuildVector(VT, DL, Result); 1573 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1574 return Result; 1575 } 1576 1577 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1578 bool isTarget) { 1579 EVT EltVT = VT.getScalarType(); 1580 if (EltVT == MVT::f32) 1581 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1582 if (EltVT == MVT::f64) 1583 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1584 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1585 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1586 bool Ignored; 1587 APFloat APF = APFloat(Val); 1588 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1589 &Ignored); 1590 return getConstantFP(APF, DL, VT, isTarget); 1591 } 1592 llvm_unreachable("Unsupported type in getConstantFP"); 1593 } 1594 1595 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1596 EVT VT, int64_t Offset, bool isTargetGA, 1597 unsigned TargetFlags) { 1598 assert((TargetFlags == 0 || isTargetGA) && 1599 "Cannot set target flags on target-independent globals"); 1600 1601 // Truncate (with sign-extension) the offset value to the pointer size. 1602 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1603 if (BitWidth < 64) 1604 Offset = SignExtend64(Offset, BitWidth); 1605 1606 unsigned Opc; 1607 if (GV->isThreadLocal()) 1608 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1609 else 1610 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1611 1612 FoldingSetNodeID ID; 1613 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1614 ID.AddPointer(GV); 1615 ID.AddInteger(Offset); 1616 ID.AddInteger(TargetFlags); 1617 void *IP = nullptr; 1618 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1619 return SDValue(E, 0); 1620 1621 auto *N = newSDNode<GlobalAddressSDNode>( 1622 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1623 CSEMap.InsertNode(N, IP); 1624 InsertNode(N); 1625 return SDValue(N, 0); 1626 } 1627 1628 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1629 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1630 FoldingSetNodeID ID; 1631 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1632 ID.AddInteger(FI); 1633 void *IP = nullptr; 1634 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1635 return SDValue(E, 0); 1636 1637 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1638 CSEMap.InsertNode(N, IP); 1639 InsertNode(N); 1640 return SDValue(N, 0); 1641 } 1642 1643 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1644 unsigned TargetFlags) { 1645 assert((TargetFlags == 0 || isTarget) && 1646 "Cannot set target flags on target-independent jump tables"); 1647 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1648 FoldingSetNodeID ID; 1649 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1650 ID.AddInteger(JTI); 1651 ID.AddInteger(TargetFlags); 1652 void *IP = nullptr; 1653 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1654 return SDValue(E, 0); 1655 1656 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1657 CSEMap.InsertNode(N, IP); 1658 InsertNode(N); 1659 return SDValue(N, 0); 1660 } 1661 1662 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1663 MaybeAlign Alignment, int Offset, 1664 bool isTarget, unsigned TargetFlags) { 1665 assert((TargetFlags == 0 || isTarget) && 1666 "Cannot set target flags on target-independent globals"); 1667 if (!Alignment) 1668 Alignment = shouldOptForSize() 1669 ? getDataLayout().getABITypeAlign(C->getType()) 1670 : getDataLayout().getPrefTypeAlign(C->getType()); 1671 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1672 FoldingSetNodeID ID; 1673 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1674 ID.AddInteger(Alignment->value()); 1675 ID.AddInteger(Offset); 1676 ID.AddPointer(C); 1677 ID.AddInteger(TargetFlags); 1678 void *IP = nullptr; 1679 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1680 return SDValue(E, 0); 1681 1682 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1683 TargetFlags); 1684 CSEMap.InsertNode(N, IP); 1685 InsertNode(N); 1686 SDValue V = SDValue(N, 0); 1687 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1688 return V; 1689 } 1690 1691 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1692 MaybeAlign Alignment, int Offset, 1693 bool isTarget, unsigned TargetFlags) { 1694 assert((TargetFlags == 0 || isTarget) && 1695 "Cannot set target flags on target-independent globals"); 1696 if (!Alignment) 1697 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1698 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(Alignment->value()); 1702 ID.AddInteger(Offset); 1703 C->addSelectionDAGCSEId(ID); 1704 ID.AddInteger(TargetFlags); 1705 void *IP = nullptr; 1706 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1707 return SDValue(E, 0); 1708 1709 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1710 TargetFlags); 1711 CSEMap.InsertNode(N, IP); 1712 InsertNode(N); 1713 return SDValue(N, 0); 1714 } 1715 1716 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1717 unsigned TargetFlags) { 1718 FoldingSetNodeID ID; 1719 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1720 ID.AddInteger(Index); 1721 ID.AddInteger(Offset); 1722 ID.AddInteger(TargetFlags); 1723 void *IP = nullptr; 1724 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1725 return SDValue(E, 0); 1726 1727 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1728 CSEMap.InsertNode(N, IP); 1729 InsertNode(N); 1730 return SDValue(N, 0); 1731 } 1732 1733 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1734 FoldingSetNodeID ID; 1735 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1736 ID.AddPointer(MBB); 1737 void *IP = nullptr; 1738 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1739 return SDValue(E, 0); 1740 1741 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1742 CSEMap.InsertNode(N, IP); 1743 InsertNode(N); 1744 return SDValue(N, 0); 1745 } 1746 1747 SDValue SelectionDAG::getValueType(EVT VT) { 1748 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1749 ValueTypeNodes.size()) 1750 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1751 1752 SDNode *&N = VT.isExtended() ? 1753 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1754 1755 if (N) return SDValue(N, 0); 1756 N = newSDNode<VTSDNode>(VT); 1757 InsertNode(N); 1758 return SDValue(N, 0); 1759 } 1760 1761 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1762 SDNode *&N = ExternalSymbols[Sym]; 1763 if (N) return SDValue(N, 0); 1764 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1765 InsertNode(N); 1766 return SDValue(N, 0); 1767 } 1768 1769 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1770 SDNode *&N = MCSymbols[Sym]; 1771 if (N) 1772 return SDValue(N, 0); 1773 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1774 InsertNode(N); 1775 return SDValue(N, 0); 1776 } 1777 1778 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1779 unsigned TargetFlags) { 1780 SDNode *&N = 1781 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1782 if (N) return SDValue(N, 0); 1783 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1784 InsertNode(N); 1785 return SDValue(N, 0); 1786 } 1787 1788 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1789 if ((unsigned)Cond >= CondCodeNodes.size()) 1790 CondCodeNodes.resize(Cond+1); 1791 1792 if (!CondCodeNodes[Cond]) { 1793 auto *N = newSDNode<CondCodeSDNode>(Cond); 1794 CondCodeNodes[Cond] = N; 1795 InsertNode(N); 1796 } 1797 1798 return SDValue(CondCodeNodes[Cond], 0); 1799 } 1800 1801 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1802 APInt One(ResVT.getScalarSizeInBits(), 1); 1803 return getStepVector(DL, ResVT, One); 1804 } 1805 1806 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1807 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1808 if (ResVT.isScalableVector()) 1809 return getNode( 1810 ISD::STEP_VECTOR, DL, ResVT, 1811 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1812 1813 SmallVector<SDValue, 16> OpsStepConstants; 1814 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1815 OpsStepConstants.push_back( 1816 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1817 return getBuildVector(ResVT, DL, OpsStepConstants); 1818 } 1819 1820 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1821 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1822 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1823 std::swap(N1, N2); 1824 ShuffleVectorSDNode::commuteMask(M); 1825 } 1826 1827 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1828 SDValue N2, ArrayRef<int> Mask) { 1829 assert(VT.getVectorNumElements() == Mask.size() && 1830 "Must have the same number of vector elements as mask elements!"); 1831 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1832 "Invalid VECTOR_SHUFFLE"); 1833 1834 // Canonicalize shuffle undef, undef -> undef 1835 if (N1.isUndef() && N2.isUndef()) 1836 return getUNDEF(VT); 1837 1838 // Validate that all indices in Mask are within the range of the elements 1839 // input to the shuffle. 1840 int NElts = Mask.size(); 1841 assert(llvm::all_of(Mask, 1842 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1843 "Index out of range"); 1844 1845 // Copy the mask so we can do any needed cleanup. 1846 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1847 1848 // Canonicalize shuffle v, v -> v, undef 1849 if (N1 == N2) { 1850 N2 = getUNDEF(VT); 1851 for (int i = 0; i != NElts; ++i) 1852 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1853 } 1854 1855 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1856 if (N1.isUndef()) 1857 commuteShuffle(N1, N2, MaskVec); 1858 1859 if (TLI->hasVectorBlend()) { 1860 // If shuffling a splat, try to blend the splat instead. We do this here so 1861 // that even when this arises during lowering we don't have to re-handle it. 1862 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1863 BitVector UndefElements; 1864 SDValue Splat = BV->getSplatValue(&UndefElements); 1865 if (!Splat) 1866 return; 1867 1868 for (int i = 0; i < NElts; ++i) { 1869 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1870 continue; 1871 1872 // If this input comes from undef, mark it as such. 1873 if (UndefElements[MaskVec[i] - Offset]) { 1874 MaskVec[i] = -1; 1875 continue; 1876 } 1877 1878 // If we can blend a non-undef lane, use that instead. 1879 if (!UndefElements[i]) 1880 MaskVec[i] = i + Offset; 1881 } 1882 }; 1883 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1884 BlendSplat(N1BV, 0); 1885 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1886 BlendSplat(N2BV, NElts); 1887 } 1888 1889 // Canonicalize all index into lhs, -> shuffle lhs, undef 1890 // Canonicalize all index into rhs, -> shuffle rhs, undef 1891 bool AllLHS = true, AllRHS = true; 1892 bool N2Undef = N2.isUndef(); 1893 for (int i = 0; i != NElts; ++i) { 1894 if (MaskVec[i] >= NElts) { 1895 if (N2Undef) 1896 MaskVec[i] = -1; 1897 else 1898 AllLHS = false; 1899 } else if (MaskVec[i] >= 0) { 1900 AllRHS = false; 1901 } 1902 } 1903 if (AllLHS && AllRHS) 1904 return getUNDEF(VT); 1905 if (AllLHS && !N2Undef) 1906 N2 = getUNDEF(VT); 1907 if (AllRHS) { 1908 N1 = getUNDEF(VT); 1909 commuteShuffle(N1, N2, MaskVec); 1910 } 1911 // Reset our undef status after accounting for the mask. 1912 N2Undef = N2.isUndef(); 1913 // Re-check whether both sides ended up undef. 1914 if (N1.isUndef() && N2Undef) 1915 return getUNDEF(VT); 1916 1917 // If Identity shuffle return that node. 1918 bool Identity = true, AllSame = true; 1919 for (int i = 0; i != NElts; ++i) { 1920 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1921 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1922 } 1923 if (Identity && NElts) 1924 return N1; 1925 1926 // Shuffling a constant splat doesn't change the result. 1927 if (N2Undef) { 1928 SDValue V = N1; 1929 1930 // Look through any bitcasts. We check that these don't change the number 1931 // (and size) of elements and just changes their types. 1932 while (V.getOpcode() == ISD::BITCAST) 1933 V = V->getOperand(0); 1934 1935 // A splat should always show up as a build vector node. 1936 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1937 BitVector UndefElements; 1938 SDValue Splat = BV->getSplatValue(&UndefElements); 1939 // If this is a splat of an undef, shuffling it is also undef. 1940 if (Splat && Splat.isUndef()) 1941 return getUNDEF(VT); 1942 1943 bool SameNumElts = 1944 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1945 1946 // We only have a splat which can skip shuffles if there is a splatted 1947 // value and no undef lanes rearranged by the shuffle. 1948 if (Splat && UndefElements.none()) { 1949 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1950 // number of elements match or the value splatted is a zero constant. 1951 if (SameNumElts) 1952 return N1; 1953 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1954 if (C->isZero()) 1955 return N1; 1956 } 1957 1958 // If the shuffle itself creates a splat, build the vector directly. 1959 if (AllSame && SameNumElts) { 1960 EVT BuildVT = BV->getValueType(0); 1961 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1962 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1963 1964 // We may have jumped through bitcasts, so the type of the 1965 // BUILD_VECTOR may not match the type of the shuffle. 1966 if (BuildVT != VT) 1967 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1968 return NewBV; 1969 } 1970 } 1971 } 1972 1973 FoldingSetNodeID ID; 1974 SDValue Ops[2] = { N1, N2 }; 1975 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1976 for (int i = 0; i != NElts; ++i) 1977 ID.AddInteger(MaskVec[i]); 1978 1979 void* IP = nullptr; 1980 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1981 return SDValue(E, 0); 1982 1983 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1984 // SDNode doesn't have access to it. This memory will be "leaked" when 1985 // the node is deallocated, but recovered when the NodeAllocator is released. 1986 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1987 llvm::copy(MaskVec, MaskAlloc); 1988 1989 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1990 dl.getDebugLoc(), MaskAlloc); 1991 createOperands(N, Ops); 1992 1993 CSEMap.InsertNode(N, IP); 1994 InsertNode(N); 1995 SDValue V = SDValue(N, 0); 1996 NewSDValueDbgMsg(V, "Creating new node: ", this); 1997 return V; 1998 } 1999 2000 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2001 EVT VT = SV.getValueType(0); 2002 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2003 ShuffleVectorSDNode::commuteMask(MaskVec); 2004 2005 SDValue Op0 = SV.getOperand(0); 2006 SDValue Op1 = SV.getOperand(1); 2007 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2008 } 2009 2010 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2011 FoldingSetNodeID ID; 2012 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2013 ID.AddInteger(RegNo); 2014 void *IP = nullptr; 2015 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2016 return SDValue(E, 0); 2017 2018 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2019 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2020 CSEMap.InsertNode(N, IP); 2021 InsertNode(N); 2022 return SDValue(N, 0); 2023 } 2024 2025 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2026 FoldingSetNodeID ID; 2027 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2028 ID.AddPointer(RegMask); 2029 void *IP = nullptr; 2030 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2031 return SDValue(E, 0); 2032 2033 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2034 CSEMap.InsertNode(N, IP); 2035 InsertNode(N); 2036 return SDValue(N, 0); 2037 } 2038 2039 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2040 MCSymbol *Label) { 2041 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2042 } 2043 2044 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2045 SDValue Root, MCSymbol *Label) { 2046 FoldingSetNodeID ID; 2047 SDValue Ops[] = { Root }; 2048 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2049 ID.AddPointer(Label); 2050 void *IP = nullptr; 2051 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2052 return SDValue(E, 0); 2053 2054 auto *N = 2055 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2056 createOperands(N, Ops); 2057 2058 CSEMap.InsertNode(N, IP); 2059 InsertNode(N); 2060 return SDValue(N, 0); 2061 } 2062 2063 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2064 int64_t Offset, bool isTarget, 2065 unsigned TargetFlags) { 2066 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2067 2068 FoldingSetNodeID ID; 2069 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2070 ID.AddPointer(BA); 2071 ID.AddInteger(Offset); 2072 ID.AddInteger(TargetFlags); 2073 void *IP = nullptr; 2074 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2075 return SDValue(E, 0); 2076 2077 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2078 CSEMap.InsertNode(N, IP); 2079 InsertNode(N); 2080 return SDValue(N, 0); 2081 } 2082 2083 SDValue SelectionDAG::getSrcValue(const Value *V) { 2084 FoldingSetNodeID ID; 2085 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2086 ID.AddPointer(V); 2087 2088 void *IP = nullptr; 2089 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2090 return SDValue(E, 0); 2091 2092 auto *N = newSDNode<SrcValueSDNode>(V); 2093 CSEMap.InsertNode(N, IP); 2094 InsertNode(N); 2095 return SDValue(N, 0); 2096 } 2097 2098 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2099 FoldingSetNodeID ID; 2100 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2101 ID.AddPointer(MD); 2102 2103 void *IP = nullptr; 2104 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2105 return SDValue(E, 0); 2106 2107 auto *N = newSDNode<MDNodeSDNode>(MD); 2108 CSEMap.InsertNode(N, IP); 2109 InsertNode(N); 2110 return SDValue(N, 0); 2111 } 2112 2113 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2114 if (VT == V.getValueType()) 2115 return V; 2116 2117 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2118 } 2119 2120 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2121 unsigned SrcAS, unsigned DestAS) { 2122 SDValue Ops[] = {Ptr}; 2123 FoldingSetNodeID ID; 2124 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2125 ID.AddInteger(SrcAS); 2126 ID.AddInteger(DestAS); 2127 2128 void *IP = nullptr; 2129 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2130 return SDValue(E, 0); 2131 2132 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2133 VT, SrcAS, DestAS); 2134 createOperands(N, Ops); 2135 2136 CSEMap.InsertNode(N, IP); 2137 InsertNode(N); 2138 return SDValue(N, 0); 2139 } 2140 2141 SDValue SelectionDAG::getFreeze(SDValue V) { 2142 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2143 } 2144 2145 /// getShiftAmountOperand - Return the specified value casted to 2146 /// the target's desired shift amount type. 2147 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2148 EVT OpTy = Op.getValueType(); 2149 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2150 if (OpTy == ShTy || OpTy.isVector()) return Op; 2151 2152 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2153 } 2154 2155 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2156 SDLoc dl(Node); 2157 const TargetLowering &TLI = getTargetLoweringInfo(); 2158 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2159 EVT VT = Node->getValueType(0); 2160 SDValue Tmp1 = Node->getOperand(0); 2161 SDValue Tmp2 = Node->getOperand(1); 2162 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2163 2164 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2165 Tmp2, MachinePointerInfo(V)); 2166 SDValue VAList = VAListLoad; 2167 2168 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2169 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2170 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2171 2172 VAList = 2173 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2174 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2175 } 2176 2177 // Increment the pointer, VAList, to the next vaarg 2178 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2179 getConstant(getDataLayout().getTypeAllocSize( 2180 VT.getTypeForEVT(*getContext())), 2181 dl, VAList.getValueType())); 2182 // Store the incremented VAList to the legalized pointer 2183 Tmp1 = 2184 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2185 // Load the actual argument out of the pointer VAList 2186 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2187 } 2188 2189 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2190 SDLoc dl(Node); 2191 const TargetLowering &TLI = getTargetLoweringInfo(); 2192 // This defaults to loading a pointer from the input and storing it to the 2193 // output, returning the chain. 2194 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2195 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2196 SDValue Tmp1 = 2197 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2198 Node->getOperand(2), MachinePointerInfo(VS)); 2199 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2200 MachinePointerInfo(VD)); 2201 } 2202 2203 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2204 const DataLayout &DL = getDataLayout(); 2205 Type *Ty = VT.getTypeForEVT(*getContext()); 2206 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2207 2208 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2209 return RedAlign; 2210 2211 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2212 const Align StackAlign = TFI->getStackAlign(); 2213 2214 // See if we can choose a smaller ABI alignment in cases where it's an 2215 // illegal vector type that will get broken down. 2216 if (RedAlign > StackAlign) { 2217 EVT IntermediateVT; 2218 MVT RegisterVT; 2219 unsigned NumIntermediates; 2220 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2221 NumIntermediates, RegisterVT); 2222 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2223 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2224 if (RedAlign2 < RedAlign) 2225 RedAlign = RedAlign2; 2226 } 2227 2228 return RedAlign; 2229 } 2230 2231 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2232 MachineFrameInfo &MFI = MF->getFrameInfo(); 2233 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2234 int StackID = 0; 2235 if (Bytes.isScalable()) 2236 StackID = TFI->getStackIDForScalableVectors(); 2237 // The stack id gives an indication of whether the object is scalable or 2238 // not, so it's safe to pass in the minimum size here. 2239 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2240 false, nullptr, StackID); 2241 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2242 } 2243 2244 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2245 Type *Ty = VT.getTypeForEVT(*getContext()); 2246 Align StackAlign = 2247 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2248 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2249 } 2250 2251 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2252 TypeSize VT1Size = VT1.getStoreSize(); 2253 TypeSize VT2Size = VT2.getStoreSize(); 2254 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2255 "Don't know how to choose the maximum size when creating a stack " 2256 "temporary"); 2257 TypeSize Bytes = 2258 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2259 2260 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2261 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2262 const DataLayout &DL = getDataLayout(); 2263 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2264 return CreateStackTemporary(Bytes, Align); 2265 } 2266 2267 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2268 ISD::CondCode Cond, const SDLoc &dl) { 2269 EVT OpVT = N1.getValueType(); 2270 2271 // These setcc operations always fold. 2272 switch (Cond) { 2273 default: break; 2274 case ISD::SETFALSE: 2275 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2276 case ISD::SETTRUE: 2277 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2278 2279 case ISD::SETOEQ: 2280 case ISD::SETOGT: 2281 case ISD::SETOGE: 2282 case ISD::SETOLT: 2283 case ISD::SETOLE: 2284 case ISD::SETONE: 2285 case ISD::SETO: 2286 case ISD::SETUO: 2287 case ISD::SETUEQ: 2288 case ISD::SETUNE: 2289 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2290 break; 2291 } 2292 2293 if (OpVT.isInteger()) { 2294 // For EQ and NE, we can always pick a value for the undef to make the 2295 // predicate pass or fail, so we can return undef. 2296 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2297 // icmp eq/ne X, undef -> undef. 2298 if ((N1.isUndef() || N2.isUndef()) && 2299 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2300 return getUNDEF(VT); 2301 2302 // If both operands are undef, we can return undef for int comparison. 2303 // icmp undef, undef -> undef. 2304 if (N1.isUndef() && N2.isUndef()) 2305 return getUNDEF(VT); 2306 2307 // icmp X, X -> true/false 2308 // icmp X, undef -> true/false because undef could be X. 2309 if (N1 == N2) 2310 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2311 } 2312 2313 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2314 const APInt &C2 = N2C->getAPIntValue(); 2315 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2316 const APInt &C1 = N1C->getAPIntValue(); 2317 2318 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2319 dl, VT, OpVT); 2320 } 2321 } 2322 2323 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2324 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2325 2326 if (N1CFP && N2CFP) { 2327 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2328 switch (Cond) { 2329 default: break; 2330 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2331 return getUNDEF(VT); 2332 LLVM_FALLTHROUGH; 2333 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2334 OpVT); 2335 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2336 return getUNDEF(VT); 2337 LLVM_FALLTHROUGH; 2338 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2339 R==APFloat::cmpLessThan, dl, VT, 2340 OpVT); 2341 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2342 return getUNDEF(VT); 2343 LLVM_FALLTHROUGH; 2344 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2345 OpVT); 2346 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2347 return getUNDEF(VT); 2348 LLVM_FALLTHROUGH; 2349 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2350 VT, OpVT); 2351 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2352 return getUNDEF(VT); 2353 LLVM_FALLTHROUGH; 2354 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2355 R==APFloat::cmpEqual, dl, VT, 2356 OpVT); 2357 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2358 return getUNDEF(VT); 2359 LLVM_FALLTHROUGH; 2360 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2361 R==APFloat::cmpEqual, dl, VT, OpVT); 2362 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2363 OpVT); 2364 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2365 OpVT); 2366 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2367 R==APFloat::cmpEqual, dl, VT, 2368 OpVT); 2369 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2370 OpVT); 2371 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2372 R==APFloat::cmpLessThan, dl, VT, 2373 OpVT); 2374 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2375 R==APFloat::cmpUnordered, dl, VT, 2376 OpVT); 2377 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2378 VT, OpVT); 2379 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2380 OpVT); 2381 } 2382 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2383 // Ensure that the constant occurs on the RHS. 2384 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2385 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2386 return SDValue(); 2387 return getSetCC(dl, VT, N2, N1, SwappedCond); 2388 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2389 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2390 // If an operand is known to be a nan (or undef that could be a nan), we can 2391 // fold it. 2392 // Choosing NaN for the undef will always make unordered comparison succeed 2393 // and ordered comparison fails. 2394 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2395 switch (ISD::getUnorderedFlavor(Cond)) { 2396 default: 2397 llvm_unreachable("Unknown flavor!"); 2398 case 0: // Known false. 2399 return getBoolConstant(false, dl, VT, OpVT); 2400 case 1: // Known true. 2401 return getBoolConstant(true, dl, VT, OpVT); 2402 case 2: // Undefined. 2403 return getUNDEF(VT); 2404 } 2405 } 2406 2407 // Could not fold it. 2408 return SDValue(); 2409 } 2410 2411 /// See if the specified operand can be simplified with the knowledge that only 2412 /// the bits specified by DemandedBits are used. 2413 /// TODO: really we should be making this into the DAG equivalent of 2414 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2415 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2416 EVT VT = V.getValueType(); 2417 2418 if (VT.isScalableVector()) 2419 return SDValue(); 2420 2421 APInt DemandedElts = VT.isVector() 2422 ? APInt::getAllOnes(VT.getVectorNumElements()) 2423 : APInt(1, 1); 2424 return GetDemandedBits(V, DemandedBits, DemandedElts); 2425 } 2426 2427 /// See if the specified operand can be simplified with the knowledge that only 2428 /// the bits specified by DemandedBits are used in the elements specified by 2429 /// DemandedElts. 2430 /// TODO: really we should be making this into the DAG equivalent of 2431 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2432 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2433 const APInt &DemandedElts) { 2434 switch (V.getOpcode()) { 2435 default: 2436 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2437 *this, 0); 2438 case ISD::Constant: { 2439 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2440 APInt NewVal = CVal & DemandedBits; 2441 if (NewVal != CVal) 2442 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2443 break; 2444 } 2445 case ISD::SRL: 2446 // Only look at single-use SRLs. 2447 if (!V.getNode()->hasOneUse()) 2448 break; 2449 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2450 // See if we can recursively simplify the LHS. 2451 unsigned Amt = RHSC->getZExtValue(); 2452 2453 // Watch out for shift count overflow though. 2454 if (Amt >= DemandedBits.getBitWidth()) 2455 break; 2456 APInt SrcDemandedBits = DemandedBits << Amt; 2457 if (SDValue SimplifyLHS = 2458 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2459 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2460 V.getOperand(1)); 2461 } 2462 break; 2463 } 2464 return SDValue(); 2465 } 2466 2467 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2468 /// use this predicate to simplify operations downstream. 2469 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2470 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2471 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2472 } 2473 2474 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2475 /// this predicate to simplify operations downstream. Mask is known to be zero 2476 /// for bits that V cannot have. 2477 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2478 unsigned Depth) const { 2479 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2480 } 2481 2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2483 /// DemandedElts. We use this predicate to simplify operations downstream. 2484 /// Mask is known to be zero for bits that V cannot have. 2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2486 const APInt &DemandedElts, 2487 unsigned Depth) const { 2488 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2489 } 2490 2491 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2492 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2493 unsigned Depth) const { 2494 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2495 } 2496 2497 /// isSplatValue - Return true if the vector V has the same value 2498 /// across all DemandedElts. For scalable vectors it does not make 2499 /// sense to specify which elements are demanded or undefined, therefore 2500 /// they are simply ignored. 2501 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2502 APInt &UndefElts, unsigned Depth) { 2503 EVT VT = V.getValueType(); 2504 assert(VT.isVector() && "Vector type expected"); 2505 2506 if (!VT.isScalableVector() && !DemandedElts) 2507 return false; // No demanded elts, better to assume we don't know anything. 2508 2509 if (Depth >= MaxRecursionDepth) 2510 return false; // Limit search depth. 2511 2512 // Deal with some common cases here that work for both fixed and scalable 2513 // vector types. 2514 switch (V.getOpcode()) { 2515 case ISD::SPLAT_VECTOR: 2516 UndefElts = V.getOperand(0).isUndef() 2517 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2518 : APInt(DemandedElts.getBitWidth(), 0); 2519 return true; 2520 case ISD::ADD: 2521 case ISD::SUB: 2522 case ISD::AND: 2523 case ISD::XOR: 2524 case ISD::OR: { 2525 APInt UndefLHS, UndefRHS; 2526 SDValue LHS = V.getOperand(0); 2527 SDValue RHS = V.getOperand(1); 2528 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2529 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2530 UndefElts = UndefLHS | UndefRHS; 2531 return true; 2532 } 2533 return false; 2534 } 2535 case ISD::ABS: 2536 case ISD::TRUNCATE: 2537 case ISD::SIGN_EXTEND: 2538 case ISD::ZERO_EXTEND: 2539 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2540 } 2541 2542 // We don't support other cases than those above for scalable vectors at 2543 // the moment. 2544 if (VT.isScalableVector()) 2545 return false; 2546 2547 unsigned NumElts = VT.getVectorNumElements(); 2548 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2549 UndefElts = APInt::getZero(NumElts); 2550 2551 switch (V.getOpcode()) { 2552 case ISD::BUILD_VECTOR: { 2553 SDValue Scl; 2554 for (unsigned i = 0; i != NumElts; ++i) { 2555 SDValue Op = V.getOperand(i); 2556 if (Op.isUndef()) { 2557 UndefElts.setBit(i); 2558 continue; 2559 } 2560 if (!DemandedElts[i]) 2561 continue; 2562 if (Scl && Scl != Op) 2563 return false; 2564 Scl = Op; 2565 } 2566 return true; 2567 } 2568 case ISD::VECTOR_SHUFFLE: { 2569 // Check if this is a shuffle node doing a splat. 2570 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2571 int SplatIndex = -1; 2572 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2573 for (int i = 0; i != (int)NumElts; ++i) { 2574 int M = Mask[i]; 2575 if (M < 0) { 2576 UndefElts.setBit(i); 2577 continue; 2578 } 2579 if (!DemandedElts[i]) 2580 continue; 2581 if (0 <= SplatIndex && SplatIndex != M) 2582 return false; 2583 SplatIndex = M; 2584 } 2585 return true; 2586 } 2587 case ISD::EXTRACT_SUBVECTOR: { 2588 // Offset the demanded elts by the subvector index. 2589 SDValue Src = V.getOperand(0); 2590 // We don't support scalable vectors at the moment. 2591 if (Src.getValueType().isScalableVector()) 2592 return false; 2593 uint64_t Idx = V.getConstantOperandVal(1); 2594 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2595 APInt UndefSrcElts; 2596 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2597 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2598 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2599 return true; 2600 } 2601 break; 2602 } 2603 } 2604 2605 return false; 2606 } 2607 2608 /// Helper wrapper to main isSplatValue function. 2609 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2610 EVT VT = V.getValueType(); 2611 assert(VT.isVector() && "Vector type expected"); 2612 2613 APInt UndefElts; 2614 APInt DemandedElts; 2615 2616 // For now we don't support this with scalable vectors. 2617 if (!VT.isScalableVector()) 2618 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2619 return isSplatValue(V, DemandedElts, UndefElts) && 2620 (AllowUndefs || !UndefElts); 2621 } 2622 2623 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2624 V = peekThroughExtractSubvectors(V); 2625 2626 EVT VT = V.getValueType(); 2627 unsigned Opcode = V.getOpcode(); 2628 switch (Opcode) { 2629 default: { 2630 APInt UndefElts; 2631 APInt DemandedElts; 2632 2633 if (!VT.isScalableVector()) 2634 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2635 2636 if (isSplatValue(V, DemandedElts, UndefElts)) { 2637 if (VT.isScalableVector()) { 2638 // DemandedElts and UndefElts are ignored for scalable vectors, since 2639 // the only supported cases are SPLAT_VECTOR nodes. 2640 SplatIdx = 0; 2641 } else { 2642 // Handle case where all demanded elements are UNDEF. 2643 if (DemandedElts.isSubsetOf(UndefElts)) { 2644 SplatIdx = 0; 2645 return getUNDEF(VT); 2646 } 2647 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2648 } 2649 return V; 2650 } 2651 break; 2652 } 2653 case ISD::SPLAT_VECTOR: 2654 SplatIdx = 0; 2655 return V; 2656 case ISD::VECTOR_SHUFFLE: { 2657 if (VT.isScalableVector()) 2658 return SDValue(); 2659 2660 // Check if this is a shuffle node doing a splat. 2661 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2662 // getTargetVShiftNode currently struggles without the splat source. 2663 auto *SVN = cast<ShuffleVectorSDNode>(V); 2664 if (!SVN->isSplat()) 2665 break; 2666 int Idx = SVN->getSplatIndex(); 2667 int NumElts = V.getValueType().getVectorNumElements(); 2668 SplatIdx = Idx % NumElts; 2669 return V.getOperand(Idx / NumElts); 2670 } 2671 } 2672 2673 return SDValue(); 2674 } 2675 2676 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2677 int SplatIdx; 2678 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2679 EVT SVT = SrcVector.getValueType().getScalarType(); 2680 EVT LegalSVT = SVT; 2681 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2682 if (!SVT.isInteger()) 2683 return SDValue(); 2684 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2685 if (LegalSVT.bitsLT(SVT)) 2686 return SDValue(); 2687 } 2688 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2689 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2690 } 2691 return SDValue(); 2692 } 2693 2694 const APInt * 2695 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2696 const APInt &DemandedElts) const { 2697 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2698 V.getOpcode() == ISD::SRA) && 2699 "Unknown shift node"); 2700 unsigned BitWidth = V.getScalarValueSizeInBits(); 2701 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2702 // Shifting more than the bitwidth is not valid. 2703 const APInt &ShAmt = SA->getAPIntValue(); 2704 if (ShAmt.ult(BitWidth)) 2705 return &ShAmt; 2706 } 2707 return nullptr; 2708 } 2709 2710 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2711 SDValue V, const APInt &DemandedElts) const { 2712 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2713 V.getOpcode() == ISD::SRA) && 2714 "Unknown shift node"); 2715 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2716 return ValidAmt; 2717 unsigned BitWidth = V.getScalarValueSizeInBits(); 2718 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2719 if (!BV) 2720 return nullptr; 2721 const APInt *MinShAmt = nullptr; 2722 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2723 if (!DemandedElts[i]) 2724 continue; 2725 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2726 if (!SA) 2727 return nullptr; 2728 // Shifting more than the bitwidth is not valid. 2729 const APInt &ShAmt = SA->getAPIntValue(); 2730 if (ShAmt.uge(BitWidth)) 2731 return nullptr; 2732 if (MinShAmt && MinShAmt->ule(ShAmt)) 2733 continue; 2734 MinShAmt = &ShAmt; 2735 } 2736 return MinShAmt; 2737 } 2738 2739 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2740 SDValue V, const APInt &DemandedElts) const { 2741 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2742 V.getOpcode() == ISD::SRA) && 2743 "Unknown shift node"); 2744 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2745 return ValidAmt; 2746 unsigned BitWidth = V.getScalarValueSizeInBits(); 2747 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2748 if (!BV) 2749 return nullptr; 2750 const APInt *MaxShAmt = nullptr; 2751 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2752 if (!DemandedElts[i]) 2753 continue; 2754 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2755 if (!SA) 2756 return nullptr; 2757 // Shifting more than the bitwidth is not valid. 2758 const APInt &ShAmt = SA->getAPIntValue(); 2759 if (ShAmt.uge(BitWidth)) 2760 return nullptr; 2761 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2762 continue; 2763 MaxShAmt = &ShAmt; 2764 } 2765 return MaxShAmt; 2766 } 2767 2768 /// Determine which bits of Op are known to be either zero or one and return 2769 /// them in Known. For vectors, the known bits are those that are shared by 2770 /// every vector element. 2771 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2772 EVT VT = Op.getValueType(); 2773 2774 // TOOD: Until we have a plan for how to represent demanded elements for 2775 // scalable vectors, we can just bail out for now. 2776 if (Op.getValueType().isScalableVector()) { 2777 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2778 return KnownBits(BitWidth); 2779 } 2780 2781 APInt DemandedElts = VT.isVector() 2782 ? APInt::getAllOnes(VT.getVectorNumElements()) 2783 : APInt(1, 1); 2784 return computeKnownBits(Op, DemandedElts, Depth); 2785 } 2786 2787 /// Determine which bits of Op are known to be either zero or one and return 2788 /// them in Known. The DemandedElts argument allows us to only collect the known 2789 /// bits that are shared by the requested vector elements. 2790 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2791 unsigned Depth) const { 2792 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2793 2794 KnownBits Known(BitWidth); // Don't know anything. 2795 2796 // TOOD: Until we have a plan for how to represent demanded elements for 2797 // scalable vectors, we can just bail out for now. 2798 if (Op.getValueType().isScalableVector()) 2799 return Known; 2800 2801 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2802 // We know all of the bits for a constant! 2803 return KnownBits::makeConstant(C->getAPIntValue()); 2804 } 2805 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2806 // We know all of the bits for a constant fp! 2807 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2808 } 2809 2810 if (Depth >= MaxRecursionDepth) 2811 return Known; // Limit search depth. 2812 2813 KnownBits Known2; 2814 unsigned NumElts = DemandedElts.getBitWidth(); 2815 assert((!Op.getValueType().isVector() || 2816 NumElts == Op.getValueType().getVectorNumElements()) && 2817 "Unexpected vector size"); 2818 2819 if (!DemandedElts) 2820 return Known; // No demanded elts, better to assume we don't know anything. 2821 2822 unsigned Opcode = Op.getOpcode(); 2823 switch (Opcode) { 2824 case ISD::BUILD_VECTOR: 2825 // Collect the known bits that are shared by every demanded vector element. 2826 Known.Zero.setAllBits(); Known.One.setAllBits(); 2827 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2828 if (!DemandedElts[i]) 2829 continue; 2830 2831 SDValue SrcOp = Op.getOperand(i); 2832 Known2 = computeKnownBits(SrcOp, Depth + 1); 2833 2834 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2835 if (SrcOp.getValueSizeInBits() != BitWidth) { 2836 assert(SrcOp.getValueSizeInBits() > BitWidth && 2837 "Expected BUILD_VECTOR implicit truncation"); 2838 Known2 = Known2.trunc(BitWidth); 2839 } 2840 2841 // Known bits are the values that are shared by every demanded element. 2842 Known = KnownBits::commonBits(Known, Known2); 2843 2844 // If we don't know any bits, early out. 2845 if (Known.isUnknown()) 2846 break; 2847 } 2848 break; 2849 case ISD::VECTOR_SHUFFLE: { 2850 // Collect the known bits that are shared by every vector element referenced 2851 // by the shuffle. 2852 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2853 Known.Zero.setAllBits(); Known.One.setAllBits(); 2854 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2855 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2856 for (unsigned i = 0; i != NumElts; ++i) { 2857 if (!DemandedElts[i]) 2858 continue; 2859 2860 int M = SVN->getMaskElt(i); 2861 if (M < 0) { 2862 // For UNDEF elements, we don't know anything about the common state of 2863 // the shuffle result. 2864 Known.resetAll(); 2865 DemandedLHS.clearAllBits(); 2866 DemandedRHS.clearAllBits(); 2867 break; 2868 } 2869 2870 if ((unsigned)M < NumElts) 2871 DemandedLHS.setBit((unsigned)M % NumElts); 2872 else 2873 DemandedRHS.setBit((unsigned)M % NumElts); 2874 } 2875 // Known bits are the values that are shared by every demanded element. 2876 if (!!DemandedLHS) { 2877 SDValue LHS = Op.getOperand(0); 2878 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2879 Known = KnownBits::commonBits(Known, Known2); 2880 } 2881 // If we don't know any bits, early out. 2882 if (Known.isUnknown()) 2883 break; 2884 if (!!DemandedRHS) { 2885 SDValue RHS = Op.getOperand(1); 2886 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2887 Known = KnownBits::commonBits(Known, Known2); 2888 } 2889 break; 2890 } 2891 case ISD::CONCAT_VECTORS: { 2892 // Split DemandedElts and test each of the demanded subvectors. 2893 Known.Zero.setAllBits(); Known.One.setAllBits(); 2894 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2895 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2896 unsigned NumSubVectors = Op.getNumOperands(); 2897 for (unsigned i = 0; i != NumSubVectors; ++i) { 2898 APInt DemandedSub = 2899 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2900 if (!!DemandedSub) { 2901 SDValue Sub = Op.getOperand(i); 2902 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2903 Known = KnownBits::commonBits(Known, Known2); 2904 } 2905 // If we don't know any bits, early out. 2906 if (Known.isUnknown()) 2907 break; 2908 } 2909 break; 2910 } 2911 case ISD::INSERT_SUBVECTOR: { 2912 // Demand any elements from the subvector and the remainder from the src its 2913 // inserted into. 2914 SDValue Src = Op.getOperand(0); 2915 SDValue Sub = Op.getOperand(1); 2916 uint64_t Idx = Op.getConstantOperandVal(2); 2917 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2918 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2919 APInt DemandedSrcElts = DemandedElts; 2920 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2921 2922 Known.One.setAllBits(); 2923 Known.Zero.setAllBits(); 2924 if (!!DemandedSubElts) { 2925 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2926 if (Known.isUnknown()) 2927 break; // early-out. 2928 } 2929 if (!!DemandedSrcElts) { 2930 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2931 Known = KnownBits::commonBits(Known, Known2); 2932 } 2933 break; 2934 } 2935 case ISD::EXTRACT_SUBVECTOR: { 2936 // Offset the demanded elts by the subvector index. 2937 SDValue Src = Op.getOperand(0); 2938 // Bail until we can represent demanded elements for scalable vectors. 2939 if (Src.getValueType().isScalableVector()) 2940 break; 2941 uint64_t Idx = Op.getConstantOperandVal(1); 2942 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2943 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2944 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2945 break; 2946 } 2947 case ISD::SCALAR_TO_VECTOR: { 2948 // We know about scalar_to_vector as much as we know about it source, 2949 // which becomes the first element of otherwise unknown vector. 2950 if (DemandedElts != 1) 2951 break; 2952 2953 SDValue N0 = Op.getOperand(0); 2954 Known = computeKnownBits(N0, Depth + 1); 2955 if (N0.getValueSizeInBits() != BitWidth) 2956 Known = Known.trunc(BitWidth); 2957 2958 break; 2959 } 2960 case ISD::BITCAST: { 2961 SDValue N0 = Op.getOperand(0); 2962 EVT SubVT = N0.getValueType(); 2963 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2964 2965 // Ignore bitcasts from unsupported types. 2966 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2967 break; 2968 2969 // Fast handling of 'identity' bitcasts. 2970 if (BitWidth == SubBitWidth) { 2971 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2972 break; 2973 } 2974 2975 bool IsLE = getDataLayout().isLittleEndian(); 2976 2977 // Bitcast 'small element' vector to 'large element' scalar/vector. 2978 if ((BitWidth % SubBitWidth) == 0) { 2979 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2980 2981 // Collect known bits for the (larger) output by collecting the known 2982 // bits from each set of sub elements and shift these into place. 2983 // We need to separately call computeKnownBits for each set of 2984 // sub elements as the knownbits for each is likely to be different. 2985 unsigned SubScale = BitWidth / SubBitWidth; 2986 APInt SubDemandedElts(NumElts * SubScale, 0); 2987 for (unsigned i = 0; i != NumElts; ++i) 2988 if (DemandedElts[i]) 2989 SubDemandedElts.setBit(i * SubScale); 2990 2991 for (unsigned i = 0; i != SubScale; ++i) { 2992 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2993 Depth + 1); 2994 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2995 Known.insertBits(Known2, SubBitWidth * Shifts); 2996 } 2997 } 2998 2999 // Bitcast 'large element' scalar/vector to 'small element' vector. 3000 if ((SubBitWidth % BitWidth) == 0) { 3001 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3002 3003 // Collect known bits for the (smaller) output by collecting the known 3004 // bits from the overlapping larger input elements and extracting the 3005 // sub sections we actually care about. 3006 unsigned SubScale = SubBitWidth / BitWidth; 3007 APInt SubDemandedElts = 3008 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3009 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3010 3011 Known.Zero.setAllBits(); Known.One.setAllBits(); 3012 for (unsigned i = 0; i != NumElts; ++i) 3013 if (DemandedElts[i]) { 3014 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3015 unsigned Offset = (Shifts % SubScale) * BitWidth; 3016 Known = KnownBits::commonBits(Known, 3017 Known2.extractBits(BitWidth, Offset)); 3018 // If we don't know any bits, early out. 3019 if (Known.isUnknown()) 3020 break; 3021 } 3022 } 3023 break; 3024 } 3025 case ISD::AND: 3026 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3027 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3028 3029 Known &= Known2; 3030 break; 3031 case ISD::OR: 3032 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3033 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3034 3035 Known |= Known2; 3036 break; 3037 case ISD::XOR: 3038 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3039 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3040 3041 Known ^= Known2; 3042 break; 3043 case ISD::MUL: { 3044 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3045 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3046 Known = KnownBits::mul(Known, Known2); 3047 break; 3048 } 3049 case ISD::MULHU: { 3050 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3051 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3052 Known = KnownBits::mulhu(Known, Known2); 3053 break; 3054 } 3055 case ISD::MULHS: { 3056 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3057 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3058 Known = KnownBits::mulhs(Known, Known2); 3059 break; 3060 } 3061 case ISD::UMUL_LOHI: { 3062 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3063 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3064 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3065 if (Op.getResNo() == 0) 3066 Known = KnownBits::mul(Known, Known2); 3067 else 3068 Known = KnownBits::mulhu(Known, Known2); 3069 break; 3070 } 3071 case ISD::SMUL_LOHI: { 3072 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3073 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3074 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3075 if (Op.getResNo() == 0) 3076 Known = KnownBits::mul(Known, Known2); 3077 else 3078 Known = KnownBits::mulhs(Known, Known2); 3079 break; 3080 } 3081 case ISD::UDIV: { 3082 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3083 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3084 Known = KnownBits::udiv(Known, Known2); 3085 break; 3086 } 3087 case ISD::SELECT: 3088 case ISD::VSELECT: 3089 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3090 // If we don't know any bits, early out. 3091 if (Known.isUnknown()) 3092 break; 3093 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3094 3095 // Only known if known in both the LHS and RHS. 3096 Known = KnownBits::commonBits(Known, Known2); 3097 break; 3098 case ISD::SELECT_CC: 3099 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3100 // If we don't know any bits, early out. 3101 if (Known.isUnknown()) 3102 break; 3103 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3104 3105 // Only known if known in both the LHS and RHS. 3106 Known = KnownBits::commonBits(Known, Known2); 3107 break; 3108 case ISD::SMULO: 3109 case ISD::UMULO: 3110 if (Op.getResNo() != 1) 3111 break; 3112 // The boolean result conforms to getBooleanContents. 3113 // If we know the result of a setcc has the top bits zero, use this info. 3114 // We know that we have an integer-based boolean since these operations 3115 // are only available for integer. 3116 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3117 TargetLowering::ZeroOrOneBooleanContent && 3118 BitWidth > 1) 3119 Known.Zero.setBitsFrom(1); 3120 break; 3121 case ISD::SETCC: 3122 case ISD::STRICT_FSETCC: 3123 case ISD::STRICT_FSETCCS: { 3124 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3125 // If we know the result of a setcc has the top bits zero, use this info. 3126 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3127 TargetLowering::ZeroOrOneBooleanContent && 3128 BitWidth > 1) 3129 Known.Zero.setBitsFrom(1); 3130 break; 3131 } 3132 case ISD::SHL: 3133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3134 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3135 Known = KnownBits::shl(Known, Known2); 3136 3137 // Minimum shift low bits are known zero. 3138 if (const APInt *ShMinAmt = 3139 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3140 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3141 break; 3142 case ISD::SRL: 3143 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3144 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3145 Known = KnownBits::lshr(Known, Known2); 3146 3147 // Minimum shift high bits are known zero. 3148 if (const APInt *ShMinAmt = 3149 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3150 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3151 break; 3152 case ISD::SRA: 3153 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3155 Known = KnownBits::ashr(Known, Known2); 3156 // TODO: Add minimum shift high known sign bits. 3157 break; 3158 case ISD::FSHL: 3159 case ISD::FSHR: 3160 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3161 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3162 3163 // For fshl, 0-shift returns the 1st arg. 3164 // For fshr, 0-shift returns the 2nd arg. 3165 if (Amt == 0) { 3166 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3167 DemandedElts, Depth + 1); 3168 break; 3169 } 3170 3171 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3172 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3173 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3174 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3175 if (Opcode == ISD::FSHL) { 3176 Known.One <<= Amt; 3177 Known.Zero <<= Amt; 3178 Known2.One.lshrInPlace(BitWidth - Amt); 3179 Known2.Zero.lshrInPlace(BitWidth - Amt); 3180 } else { 3181 Known.One <<= BitWidth - Amt; 3182 Known.Zero <<= BitWidth - Amt; 3183 Known2.One.lshrInPlace(Amt); 3184 Known2.Zero.lshrInPlace(Amt); 3185 } 3186 Known.One |= Known2.One; 3187 Known.Zero |= Known2.Zero; 3188 } 3189 break; 3190 case ISD::SIGN_EXTEND_INREG: { 3191 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3192 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3193 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3194 break; 3195 } 3196 case ISD::CTTZ: 3197 case ISD::CTTZ_ZERO_UNDEF: { 3198 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3199 // If we have a known 1, its position is our upper bound. 3200 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3201 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3202 Known.Zero.setBitsFrom(LowBits); 3203 break; 3204 } 3205 case ISD::CTLZ: 3206 case ISD::CTLZ_ZERO_UNDEF: { 3207 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3208 // If we have a known 1, its position is our upper bound. 3209 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3210 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3211 Known.Zero.setBitsFrom(LowBits); 3212 break; 3213 } 3214 case ISD::CTPOP: { 3215 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 // If we know some of the bits are zero, they can't be one. 3217 unsigned PossibleOnes = Known2.countMaxPopulation(); 3218 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3219 break; 3220 } 3221 case ISD::PARITY: { 3222 // Parity returns 0 everywhere but the LSB. 3223 Known.Zero.setBitsFrom(1); 3224 break; 3225 } 3226 case ISD::LOAD: { 3227 LoadSDNode *LD = cast<LoadSDNode>(Op); 3228 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3229 if (ISD::isNON_EXTLoad(LD) && Cst) { 3230 // Determine any common known bits from the loaded constant pool value. 3231 Type *CstTy = Cst->getType(); 3232 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3233 // If its a vector splat, then we can (quickly) reuse the scalar path. 3234 // NOTE: We assume all elements match and none are UNDEF. 3235 if (CstTy->isVectorTy()) { 3236 if (const Constant *Splat = Cst->getSplatValue()) { 3237 Cst = Splat; 3238 CstTy = Cst->getType(); 3239 } 3240 } 3241 // TODO - do we need to handle different bitwidths? 3242 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3243 // Iterate across all vector elements finding common known bits. 3244 Known.One.setAllBits(); 3245 Known.Zero.setAllBits(); 3246 for (unsigned i = 0; i != NumElts; ++i) { 3247 if (!DemandedElts[i]) 3248 continue; 3249 if (Constant *Elt = Cst->getAggregateElement(i)) { 3250 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3251 const APInt &Value = CInt->getValue(); 3252 Known.One &= Value; 3253 Known.Zero &= ~Value; 3254 continue; 3255 } 3256 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3257 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3258 Known.One &= Value; 3259 Known.Zero &= ~Value; 3260 continue; 3261 } 3262 } 3263 Known.One.clearAllBits(); 3264 Known.Zero.clearAllBits(); 3265 break; 3266 } 3267 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3268 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3269 Known = KnownBits::makeConstant(CInt->getValue()); 3270 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3271 Known = 3272 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3273 } 3274 } 3275 } 3276 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3277 // If this is a ZEXTLoad and we are looking at the loaded value. 3278 EVT VT = LD->getMemoryVT(); 3279 unsigned MemBits = VT.getScalarSizeInBits(); 3280 Known.Zero.setBitsFrom(MemBits); 3281 } else if (const MDNode *Ranges = LD->getRanges()) { 3282 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3283 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3284 } 3285 break; 3286 } 3287 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3288 EVT InVT = Op.getOperand(0).getValueType(); 3289 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3290 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3291 Known = Known.zext(BitWidth); 3292 break; 3293 } 3294 case ISD::ZERO_EXTEND: { 3295 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3296 Known = Known.zext(BitWidth); 3297 break; 3298 } 3299 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3300 EVT InVT = Op.getOperand(0).getValueType(); 3301 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3302 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3303 // If the sign bit is known to be zero or one, then sext will extend 3304 // it to the top bits, else it will just zext. 3305 Known = Known.sext(BitWidth); 3306 break; 3307 } 3308 case ISD::SIGN_EXTEND: { 3309 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3310 // If the sign bit is known to be zero or one, then sext will extend 3311 // it to the top bits, else it will just zext. 3312 Known = Known.sext(BitWidth); 3313 break; 3314 } 3315 case ISD::ANY_EXTEND_VECTOR_INREG: { 3316 EVT InVT = Op.getOperand(0).getValueType(); 3317 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3318 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3319 Known = Known.anyext(BitWidth); 3320 break; 3321 } 3322 case ISD::ANY_EXTEND: { 3323 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3324 Known = Known.anyext(BitWidth); 3325 break; 3326 } 3327 case ISD::TRUNCATE: { 3328 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3329 Known = Known.trunc(BitWidth); 3330 break; 3331 } 3332 case ISD::AssertZext: { 3333 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3334 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3335 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3336 Known.Zero |= (~InMask); 3337 Known.One &= (~Known.Zero); 3338 break; 3339 } 3340 case ISD::AssertAlign: { 3341 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3342 assert(LogOfAlign != 0); 3343 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3344 // well as clearing one bits. 3345 Known.Zero.setLowBits(LogOfAlign); 3346 Known.One.clearLowBits(LogOfAlign); 3347 break; 3348 } 3349 case ISD::FGETSIGN: 3350 // All bits are zero except the low bit. 3351 Known.Zero.setBitsFrom(1); 3352 break; 3353 case ISD::USUBO: 3354 case ISD::SSUBO: 3355 if (Op.getResNo() == 1) { 3356 // If we know the result of a setcc has the top bits zero, use this info. 3357 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3358 TargetLowering::ZeroOrOneBooleanContent && 3359 BitWidth > 1) 3360 Known.Zero.setBitsFrom(1); 3361 break; 3362 } 3363 LLVM_FALLTHROUGH; 3364 case ISD::SUB: 3365 case ISD::SUBC: { 3366 assert(Op.getResNo() == 0 && 3367 "We only compute knownbits for the difference here."); 3368 3369 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3370 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3371 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3372 Known, Known2); 3373 break; 3374 } 3375 case ISD::UADDO: 3376 case ISD::SADDO: 3377 case ISD::ADDCARRY: 3378 if (Op.getResNo() == 1) { 3379 // If we know the result of a setcc has the top bits zero, use this info. 3380 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3381 TargetLowering::ZeroOrOneBooleanContent && 3382 BitWidth > 1) 3383 Known.Zero.setBitsFrom(1); 3384 break; 3385 } 3386 LLVM_FALLTHROUGH; 3387 case ISD::ADD: 3388 case ISD::ADDC: 3389 case ISD::ADDE: { 3390 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3391 3392 // With ADDE and ADDCARRY, a carry bit may be added in. 3393 KnownBits Carry(1); 3394 if (Opcode == ISD::ADDE) 3395 // Can't track carry from glue, set carry to unknown. 3396 Carry.resetAll(); 3397 else if (Opcode == ISD::ADDCARRY) 3398 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3399 // the trouble (how often will we find a known carry bit). And I haven't 3400 // tested this very much yet, but something like this might work: 3401 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3402 // Carry = Carry.zextOrTrunc(1, false); 3403 Carry.resetAll(); 3404 else 3405 Carry.setAllZero(); 3406 3407 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3408 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3409 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3410 break; 3411 } 3412 case ISD::SREM: { 3413 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3414 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3415 Known = KnownBits::srem(Known, Known2); 3416 break; 3417 } 3418 case ISD::UREM: { 3419 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3420 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3421 Known = KnownBits::urem(Known, Known2); 3422 break; 3423 } 3424 case ISD::EXTRACT_ELEMENT: { 3425 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3426 const unsigned Index = Op.getConstantOperandVal(1); 3427 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3428 3429 // Remove low part of known bits mask 3430 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3431 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3432 3433 // Remove high part of known bit mask 3434 Known = Known.trunc(EltBitWidth); 3435 break; 3436 } 3437 case ISD::EXTRACT_VECTOR_ELT: { 3438 SDValue InVec = Op.getOperand(0); 3439 SDValue EltNo = Op.getOperand(1); 3440 EVT VecVT = InVec.getValueType(); 3441 // computeKnownBits not yet implemented for scalable vectors. 3442 if (VecVT.isScalableVector()) 3443 break; 3444 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3445 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3446 3447 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3448 // anything about the extended bits. 3449 if (BitWidth > EltBitWidth) 3450 Known = Known.trunc(EltBitWidth); 3451 3452 // If we know the element index, just demand that vector element, else for 3453 // an unknown element index, ignore DemandedElts and demand them all. 3454 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3455 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3456 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3457 DemandedSrcElts = 3458 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3459 3460 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3461 if (BitWidth > EltBitWidth) 3462 Known = Known.anyext(BitWidth); 3463 break; 3464 } 3465 case ISD::INSERT_VECTOR_ELT: { 3466 // If we know the element index, split the demand between the 3467 // source vector and the inserted element, otherwise assume we need 3468 // the original demanded vector elements and the value. 3469 SDValue InVec = Op.getOperand(0); 3470 SDValue InVal = Op.getOperand(1); 3471 SDValue EltNo = Op.getOperand(2); 3472 bool DemandedVal = true; 3473 APInt DemandedVecElts = DemandedElts; 3474 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3475 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3476 unsigned EltIdx = CEltNo->getZExtValue(); 3477 DemandedVal = !!DemandedElts[EltIdx]; 3478 DemandedVecElts.clearBit(EltIdx); 3479 } 3480 Known.One.setAllBits(); 3481 Known.Zero.setAllBits(); 3482 if (DemandedVal) { 3483 Known2 = computeKnownBits(InVal, Depth + 1); 3484 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3485 } 3486 if (!!DemandedVecElts) { 3487 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3488 Known = KnownBits::commonBits(Known, Known2); 3489 } 3490 break; 3491 } 3492 case ISD::BITREVERSE: { 3493 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3494 Known = Known2.reverseBits(); 3495 break; 3496 } 3497 case ISD::BSWAP: { 3498 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3499 Known = Known2.byteSwap(); 3500 break; 3501 } 3502 case ISD::ABS: { 3503 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3504 Known = Known2.abs(); 3505 break; 3506 } 3507 case ISD::USUBSAT: { 3508 // The result of usubsat will never be larger than the LHS. 3509 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3510 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3511 break; 3512 } 3513 case ISD::UMIN: { 3514 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3515 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3516 Known = KnownBits::umin(Known, Known2); 3517 break; 3518 } 3519 case ISD::UMAX: { 3520 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3521 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3522 Known = KnownBits::umax(Known, Known2); 3523 break; 3524 } 3525 case ISD::SMIN: 3526 case ISD::SMAX: { 3527 // If we have a clamp pattern, we know that the number of sign bits will be 3528 // the minimum of the clamp min/max range. 3529 bool IsMax = (Opcode == ISD::SMAX); 3530 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3531 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3532 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3533 CstHigh = 3534 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3535 if (CstLow && CstHigh) { 3536 if (!IsMax) 3537 std::swap(CstLow, CstHigh); 3538 3539 const APInt &ValueLow = CstLow->getAPIntValue(); 3540 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3541 if (ValueLow.sle(ValueHigh)) { 3542 unsigned LowSignBits = ValueLow.getNumSignBits(); 3543 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3544 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3545 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3546 Known.One.setHighBits(MinSignBits); 3547 break; 3548 } 3549 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3550 Known.Zero.setHighBits(MinSignBits); 3551 break; 3552 } 3553 } 3554 } 3555 3556 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3557 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3558 if (IsMax) 3559 Known = KnownBits::smax(Known, Known2); 3560 else 3561 Known = KnownBits::smin(Known, Known2); 3562 break; 3563 } 3564 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3565 if (Op.getResNo() == 1) { 3566 // The boolean result conforms to getBooleanContents. 3567 // If we know the result of a setcc has the top bits zero, use this info. 3568 // We know that we have an integer-based boolean since these operations 3569 // are only available for integer. 3570 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3571 TargetLowering::ZeroOrOneBooleanContent && 3572 BitWidth > 1) 3573 Known.Zero.setBitsFrom(1); 3574 break; 3575 } 3576 LLVM_FALLTHROUGH; 3577 case ISD::ATOMIC_CMP_SWAP: 3578 case ISD::ATOMIC_SWAP: 3579 case ISD::ATOMIC_LOAD_ADD: 3580 case ISD::ATOMIC_LOAD_SUB: 3581 case ISD::ATOMIC_LOAD_AND: 3582 case ISD::ATOMIC_LOAD_CLR: 3583 case ISD::ATOMIC_LOAD_OR: 3584 case ISD::ATOMIC_LOAD_XOR: 3585 case ISD::ATOMIC_LOAD_NAND: 3586 case ISD::ATOMIC_LOAD_MIN: 3587 case ISD::ATOMIC_LOAD_MAX: 3588 case ISD::ATOMIC_LOAD_UMIN: 3589 case ISD::ATOMIC_LOAD_UMAX: 3590 case ISD::ATOMIC_LOAD: { 3591 unsigned MemBits = 3592 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3593 // If we are looking at the loaded value. 3594 if (Op.getResNo() == 0) { 3595 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3596 Known.Zero.setBitsFrom(MemBits); 3597 } 3598 break; 3599 } 3600 case ISD::FrameIndex: 3601 case ISD::TargetFrameIndex: 3602 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3603 Known, getMachineFunction()); 3604 break; 3605 3606 default: 3607 if (Opcode < ISD::BUILTIN_OP_END) 3608 break; 3609 LLVM_FALLTHROUGH; 3610 case ISD::INTRINSIC_WO_CHAIN: 3611 case ISD::INTRINSIC_W_CHAIN: 3612 case ISD::INTRINSIC_VOID: 3613 // Allow the target to implement this method for its nodes. 3614 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3615 break; 3616 } 3617 3618 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3619 return Known; 3620 } 3621 3622 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3623 SDValue N1) const { 3624 // X + 0 never overflow 3625 if (isNullConstant(N1)) 3626 return OFK_Never; 3627 3628 KnownBits N1Known = computeKnownBits(N1); 3629 if (N1Known.Zero.getBoolValue()) { 3630 KnownBits N0Known = computeKnownBits(N0); 3631 3632 bool overflow; 3633 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3634 if (!overflow) 3635 return OFK_Never; 3636 } 3637 3638 // mulhi + 1 never overflow 3639 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3640 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3641 return OFK_Never; 3642 3643 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3644 KnownBits N0Known = computeKnownBits(N0); 3645 3646 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3647 return OFK_Never; 3648 } 3649 3650 return OFK_Sometime; 3651 } 3652 3653 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3654 EVT OpVT = Val.getValueType(); 3655 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3656 3657 // Is the constant a known power of 2? 3658 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3659 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3660 3661 // A left-shift of a constant one will have exactly one bit set because 3662 // shifting the bit off the end is undefined. 3663 if (Val.getOpcode() == ISD::SHL) { 3664 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3665 if (C && C->getAPIntValue() == 1) 3666 return true; 3667 } 3668 3669 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3670 // one bit set. 3671 if (Val.getOpcode() == ISD::SRL) { 3672 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3673 if (C && C->getAPIntValue().isSignMask()) 3674 return true; 3675 } 3676 3677 // Are all operands of a build vector constant powers of two? 3678 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3679 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3681 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3682 return false; 3683 })) 3684 return true; 3685 3686 // Is the operand of a splat vector a constant power of two? 3687 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3688 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3689 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3690 return true; 3691 3692 // More could be done here, though the above checks are enough 3693 // to handle some common cases. 3694 3695 // Fall back to computeKnownBits to catch other known cases. 3696 KnownBits Known = computeKnownBits(Val); 3697 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3698 } 3699 3700 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3701 EVT VT = Op.getValueType(); 3702 3703 // TODO: Assume we don't know anything for now. 3704 if (VT.isScalableVector()) 3705 return 1; 3706 3707 APInt DemandedElts = VT.isVector() 3708 ? APInt::getAllOnes(VT.getVectorNumElements()) 3709 : APInt(1, 1); 3710 return ComputeNumSignBits(Op, DemandedElts, Depth); 3711 } 3712 3713 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3714 unsigned Depth) const { 3715 EVT VT = Op.getValueType(); 3716 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3717 unsigned VTBits = VT.getScalarSizeInBits(); 3718 unsigned NumElts = DemandedElts.getBitWidth(); 3719 unsigned Tmp, Tmp2; 3720 unsigned FirstAnswer = 1; 3721 3722 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3723 const APInt &Val = C->getAPIntValue(); 3724 return Val.getNumSignBits(); 3725 } 3726 3727 if (Depth >= MaxRecursionDepth) 3728 return 1; // Limit search depth. 3729 3730 if (!DemandedElts || VT.isScalableVector()) 3731 return 1; // No demanded elts, better to assume we don't know anything. 3732 3733 unsigned Opcode = Op.getOpcode(); 3734 switch (Opcode) { 3735 default: break; 3736 case ISD::AssertSext: 3737 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3738 return VTBits-Tmp+1; 3739 case ISD::AssertZext: 3740 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3741 return VTBits-Tmp; 3742 3743 case ISD::BUILD_VECTOR: 3744 Tmp = VTBits; 3745 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3746 if (!DemandedElts[i]) 3747 continue; 3748 3749 SDValue SrcOp = Op.getOperand(i); 3750 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3751 3752 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3753 if (SrcOp.getValueSizeInBits() != VTBits) { 3754 assert(SrcOp.getValueSizeInBits() > VTBits && 3755 "Expected BUILD_VECTOR implicit truncation"); 3756 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3757 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3758 } 3759 Tmp = std::min(Tmp, Tmp2); 3760 } 3761 return Tmp; 3762 3763 case ISD::VECTOR_SHUFFLE: { 3764 // Collect the minimum number of sign bits that are shared by every vector 3765 // element referenced by the shuffle. 3766 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3767 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3768 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3769 for (unsigned i = 0; i != NumElts; ++i) { 3770 int M = SVN->getMaskElt(i); 3771 if (!DemandedElts[i]) 3772 continue; 3773 // For UNDEF elements, we don't know anything about the common state of 3774 // the shuffle result. 3775 if (M < 0) 3776 return 1; 3777 if ((unsigned)M < NumElts) 3778 DemandedLHS.setBit((unsigned)M % NumElts); 3779 else 3780 DemandedRHS.setBit((unsigned)M % NumElts); 3781 } 3782 Tmp = std::numeric_limits<unsigned>::max(); 3783 if (!!DemandedLHS) 3784 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3785 if (!!DemandedRHS) { 3786 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3787 Tmp = std::min(Tmp, Tmp2); 3788 } 3789 // If we don't know anything, early out and try computeKnownBits fall-back. 3790 if (Tmp == 1) 3791 break; 3792 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3793 return Tmp; 3794 } 3795 3796 case ISD::BITCAST: { 3797 SDValue N0 = Op.getOperand(0); 3798 EVT SrcVT = N0.getValueType(); 3799 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3800 3801 // Ignore bitcasts from unsupported types.. 3802 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3803 break; 3804 3805 // Fast handling of 'identity' bitcasts. 3806 if (VTBits == SrcBits) 3807 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3808 3809 bool IsLE = getDataLayout().isLittleEndian(); 3810 3811 // Bitcast 'large element' scalar/vector to 'small element' vector. 3812 if ((SrcBits % VTBits) == 0) { 3813 assert(VT.isVector() && "Expected bitcast to vector"); 3814 3815 unsigned Scale = SrcBits / VTBits; 3816 APInt SrcDemandedElts = 3817 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3818 3819 // Fast case - sign splat can be simply split across the small elements. 3820 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3821 if (Tmp == SrcBits) 3822 return VTBits; 3823 3824 // Slow case - determine how far the sign extends into each sub-element. 3825 Tmp2 = VTBits; 3826 for (unsigned i = 0; i != NumElts; ++i) 3827 if (DemandedElts[i]) { 3828 unsigned SubOffset = i % Scale; 3829 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3830 SubOffset = SubOffset * VTBits; 3831 if (Tmp <= SubOffset) 3832 return 1; 3833 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3834 } 3835 return Tmp2; 3836 } 3837 break; 3838 } 3839 3840 case ISD::SIGN_EXTEND: 3841 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3842 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3843 case ISD::SIGN_EXTEND_INREG: 3844 // Max of the input and what this extends. 3845 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3846 Tmp = VTBits-Tmp+1; 3847 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3848 return std::max(Tmp, Tmp2); 3849 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3850 SDValue Src = Op.getOperand(0); 3851 EVT SrcVT = Src.getValueType(); 3852 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3853 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3854 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3855 } 3856 case ISD::SRA: 3857 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3858 // SRA X, C -> adds C sign bits. 3859 if (const APInt *ShAmt = 3860 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3861 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3862 return Tmp; 3863 case ISD::SHL: 3864 if (const APInt *ShAmt = 3865 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3866 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3867 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3868 if (ShAmt->ult(Tmp)) 3869 return Tmp - ShAmt->getZExtValue(); 3870 } 3871 break; 3872 case ISD::AND: 3873 case ISD::OR: 3874 case ISD::XOR: // NOT is handled here. 3875 // Logical binary ops preserve the number of sign bits at the worst. 3876 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3877 if (Tmp != 1) { 3878 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3879 FirstAnswer = std::min(Tmp, Tmp2); 3880 // We computed what we know about the sign bits as our first 3881 // answer. Now proceed to the generic code that uses 3882 // computeKnownBits, and pick whichever answer is better. 3883 } 3884 break; 3885 3886 case ISD::SELECT: 3887 case ISD::VSELECT: 3888 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3889 if (Tmp == 1) return 1; // Early out. 3890 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3891 return std::min(Tmp, Tmp2); 3892 case ISD::SELECT_CC: 3893 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3894 if (Tmp == 1) return 1; // Early out. 3895 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3896 return std::min(Tmp, Tmp2); 3897 3898 case ISD::SMIN: 3899 case ISD::SMAX: { 3900 // If we have a clamp pattern, we know that the number of sign bits will be 3901 // the minimum of the clamp min/max range. 3902 bool IsMax = (Opcode == ISD::SMAX); 3903 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3904 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3905 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3906 CstHigh = 3907 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3908 if (CstLow && CstHigh) { 3909 if (!IsMax) 3910 std::swap(CstLow, CstHigh); 3911 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3912 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3913 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3914 return std::min(Tmp, Tmp2); 3915 } 3916 } 3917 3918 // Fallback - just get the minimum number of sign bits of the operands. 3919 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3920 if (Tmp == 1) 3921 return 1; // Early out. 3922 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3923 return std::min(Tmp, Tmp2); 3924 } 3925 case ISD::UMIN: 3926 case ISD::UMAX: 3927 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3928 if (Tmp == 1) 3929 return 1; // Early out. 3930 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3931 return std::min(Tmp, Tmp2); 3932 case ISD::SADDO: 3933 case ISD::UADDO: 3934 case ISD::SSUBO: 3935 case ISD::USUBO: 3936 case ISD::SMULO: 3937 case ISD::UMULO: 3938 if (Op.getResNo() != 1) 3939 break; 3940 // The boolean result conforms to getBooleanContents. Fall through. 3941 // If setcc returns 0/-1, all bits are sign bits. 3942 // We know that we have an integer-based boolean since these operations 3943 // are only available for integer. 3944 if (TLI->getBooleanContents(VT.isVector(), false) == 3945 TargetLowering::ZeroOrNegativeOneBooleanContent) 3946 return VTBits; 3947 break; 3948 case ISD::SETCC: 3949 case ISD::STRICT_FSETCC: 3950 case ISD::STRICT_FSETCCS: { 3951 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3952 // If setcc returns 0/-1, all bits are sign bits. 3953 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3954 TargetLowering::ZeroOrNegativeOneBooleanContent) 3955 return VTBits; 3956 break; 3957 } 3958 case ISD::ROTL: 3959 case ISD::ROTR: 3960 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3961 3962 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3963 if (Tmp == VTBits) 3964 return VTBits; 3965 3966 if (ConstantSDNode *C = 3967 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3968 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3969 3970 // Handle rotate right by N like a rotate left by 32-N. 3971 if (Opcode == ISD::ROTR) 3972 RotAmt = (VTBits - RotAmt) % VTBits; 3973 3974 // If we aren't rotating out all of the known-in sign bits, return the 3975 // number that are left. This handles rotl(sext(x), 1) for example. 3976 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3977 } 3978 break; 3979 case ISD::ADD: 3980 case ISD::ADDC: 3981 // Add can have at most one carry bit. Thus we know that the output 3982 // is, at worst, one more bit than the inputs. 3983 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3984 if (Tmp == 1) return 1; // Early out. 3985 3986 // Special case decrementing a value (ADD X, -1): 3987 if (ConstantSDNode *CRHS = 3988 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3989 if (CRHS->isAllOnes()) { 3990 KnownBits Known = 3991 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3992 3993 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3994 // sign bits set. 3995 if ((Known.Zero | 1).isAllOnes()) 3996 return VTBits; 3997 3998 // If we are subtracting one from a positive number, there is no carry 3999 // out of the result. 4000 if (Known.isNonNegative()) 4001 return Tmp; 4002 } 4003 4004 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4005 if (Tmp2 == 1) return 1; // Early out. 4006 return std::min(Tmp, Tmp2) - 1; 4007 case ISD::SUB: 4008 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4009 if (Tmp2 == 1) return 1; // Early out. 4010 4011 // Handle NEG. 4012 if (ConstantSDNode *CLHS = 4013 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4014 if (CLHS->isZero()) { 4015 KnownBits Known = 4016 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4017 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4018 // sign bits set. 4019 if ((Known.Zero | 1).isAllOnes()) 4020 return VTBits; 4021 4022 // If the input is known to be positive (the sign bit is known clear), 4023 // the output of the NEG has the same number of sign bits as the input. 4024 if (Known.isNonNegative()) 4025 return Tmp2; 4026 4027 // Otherwise, we treat this like a SUB. 4028 } 4029 4030 // Sub can have at most one carry bit. Thus we know that the output 4031 // is, at worst, one more bit than the inputs. 4032 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4033 if (Tmp == 1) return 1; // Early out. 4034 return std::min(Tmp, Tmp2) - 1; 4035 case ISD::MUL: { 4036 // The output of the Mul can be at most twice the valid bits in the inputs. 4037 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4038 if (SignBitsOp0 == 1) 4039 break; 4040 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4041 if (SignBitsOp1 == 1) 4042 break; 4043 unsigned OutValidBits = 4044 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4045 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4046 } 4047 case ISD::SREM: 4048 // The sign bit is the LHS's sign bit, except when the result of the 4049 // remainder is zero. The magnitude of the result should be less than or 4050 // equal to the magnitude of the LHS. Therefore, the result should have 4051 // at least as many sign bits as the left hand side. 4052 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4053 case ISD::TRUNCATE: { 4054 // Check if the sign bits of source go down as far as the truncated value. 4055 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4056 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4057 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4058 return NumSrcSignBits - (NumSrcBits - VTBits); 4059 break; 4060 } 4061 case ISD::EXTRACT_ELEMENT: { 4062 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4063 const int BitWidth = Op.getValueSizeInBits(); 4064 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4065 4066 // Get reverse index (starting from 1), Op1 value indexes elements from 4067 // little end. Sign starts at big end. 4068 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4069 4070 // If the sign portion ends in our element the subtraction gives correct 4071 // result. Otherwise it gives either negative or > bitwidth result 4072 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4073 } 4074 case ISD::INSERT_VECTOR_ELT: { 4075 // If we know the element index, split the demand between the 4076 // source vector and the inserted element, otherwise assume we need 4077 // the original demanded vector elements and the value. 4078 SDValue InVec = Op.getOperand(0); 4079 SDValue InVal = Op.getOperand(1); 4080 SDValue EltNo = Op.getOperand(2); 4081 bool DemandedVal = true; 4082 APInt DemandedVecElts = DemandedElts; 4083 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4084 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4085 unsigned EltIdx = CEltNo->getZExtValue(); 4086 DemandedVal = !!DemandedElts[EltIdx]; 4087 DemandedVecElts.clearBit(EltIdx); 4088 } 4089 Tmp = std::numeric_limits<unsigned>::max(); 4090 if (DemandedVal) { 4091 // TODO - handle implicit truncation of inserted elements. 4092 if (InVal.getScalarValueSizeInBits() != VTBits) 4093 break; 4094 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4095 Tmp = std::min(Tmp, Tmp2); 4096 } 4097 if (!!DemandedVecElts) { 4098 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4099 Tmp = std::min(Tmp, Tmp2); 4100 } 4101 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4102 return Tmp; 4103 } 4104 case ISD::EXTRACT_VECTOR_ELT: { 4105 SDValue InVec = Op.getOperand(0); 4106 SDValue EltNo = Op.getOperand(1); 4107 EVT VecVT = InVec.getValueType(); 4108 // ComputeNumSignBits not yet implemented for scalable vectors. 4109 if (VecVT.isScalableVector()) 4110 break; 4111 const unsigned BitWidth = Op.getValueSizeInBits(); 4112 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4113 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4114 4115 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4116 // anything about sign bits. But if the sizes match we can derive knowledge 4117 // about sign bits from the vector operand. 4118 if (BitWidth != EltBitWidth) 4119 break; 4120 4121 // If we know the element index, just demand that vector element, else for 4122 // an unknown element index, ignore DemandedElts and demand them all. 4123 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4124 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4125 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4126 DemandedSrcElts = 4127 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4128 4129 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4130 } 4131 case ISD::EXTRACT_SUBVECTOR: { 4132 // Offset the demanded elts by the subvector index. 4133 SDValue Src = Op.getOperand(0); 4134 // Bail until we can represent demanded elements for scalable vectors. 4135 if (Src.getValueType().isScalableVector()) 4136 break; 4137 uint64_t Idx = Op.getConstantOperandVal(1); 4138 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4139 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4140 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4141 } 4142 case ISD::CONCAT_VECTORS: { 4143 // Determine the minimum number of sign bits across all demanded 4144 // elts of the input vectors. Early out if the result is already 1. 4145 Tmp = std::numeric_limits<unsigned>::max(); 4146 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4147 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4148 unsigned NumSubVectors = Op.getNumOperands(); 4149 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4150 APInt DemandedSub = 4151 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4152 if (!DemandedSub) 4153 continue; 4154 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4155 Tmp = std::min(Tmp, Tmp2); 4156 } 4157 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4158 return Tmp; 4159 } 4160 case ISD::INSERT_SUBVECTOR: { 4161 // Demand any elements from the subvector and the remainder from the src its 4162 // inserted into. 4163 SDValue Src = Op.getOperand(0); 4164 SDValue Sub = Op.getOperand(1); 4165 uint64_t Idx = Op.getConstantOperandVal(2); 4166 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4167 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4168 APInt DemandedSrcElts = DemandedElts; 4169 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4170 4171 Tmp = std::numeric_limits<unsigned>::max(); 4172 if (!!DemandedSubElts) { 4173 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4174 if (Tmp == 1) 4175 return 1; // early-out 4176 } 4177 if (!!DemandedSrcElts) { 4178 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4179 Tmp = std::min(Tmp, Tmp2); 4180 } 4181 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4182 return Tmp; 4183 } 4184 case ISD::ATOMIC_CMP_SWAP: 4185 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4186 case ISD::ATOMIC_SWAP: 4187 case ISD::ATOMIC_LOAD_ADD: 4188 case ISD::ATOMIC_LOAD_SUB: 4189 case ISD::ATOMIC_LOAD_AND: 4190 case ISD::ATOMIC_LOAD_CLR: 4191 case ISD::ATOMIC_LOAD_OR: 4192 case ISD::ATOMIC_LOAD_XOR: 4193 case ISD::ATOMIC_LOAD_NAND: 4194 case ISD::ATOMIC_LOAD_MIN: 4195 case ISD::ATOMIC_LOAD_MAX: 4196 case ISD::ATOMIC_LOAD_UMIN: 4197 case ISD::ATOMIC_LOAD_UMAX: 4198 case ISD::ATOMIC_LOAD: { 4199 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4200 // If we are looking at the loaded value. 4201 if (Op.getResNo() == 0) { 4202 if (Tmp == VTBits) 4203 return 1; // early-out 4204 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4205 return VTBits - Tmp + 1; 4206 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4207 return VTBits - Tmp; 4208 } 4209 break; 4210 } 4211 } 4212 4213 // If we are looking at the loaded value of the SDNode. 4214 if (Op.getResNo() == 0) { 4215 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4216 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4217 unsigned ExtType = LD->getExtensionType(); 4218 switch (ExtType) { 4219 default: break; 4220 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4221 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4222 return VTBits - Tmp + 1; 4223 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4224 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4225 return VTBits - Tmp; 4226 case ISD::NON_EXTLOAD: 4227 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4228 // We only need to handle vectors - computeKnownBits should handle 4229 // scalar cases. 4230 Type *CstTy = Cst->getType(); 4231 if (CstTy->isVectorTy() && 4232 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4233 Tmp = VTBits; 4234 for (unsigned i = 0; i != NumElts; ++i) { 4235 if (!DemandedElts[i]) 4236 continue; 4237 if (Constant *Elt = Cst->getAggregateElement(i)) { 4238 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4239 const APInt &Value = CInt->getValue(); 4240 Tmp = std::min(Tmp, Value.getNumSignBits()); 4241 continue; 4242 } 4243 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4244 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4245 Tmp = std::min(Tmp, Value.getNumSignBits()); 4246 continue; 4247 } 4248 } 4249 // Unknown type. Conservatively assume no bits match sign bit. 4250 return 1; 4251 } 4252 return Tmp; 4253 } 4254 } 4255 break; 4256 } 4257 } 4258 } 4259 4260 // Allow the target to implement this method for its nodes. 4261 if (Opcode >= ISD::BUILTIN_OP_END || 4262 Opcode == ISD::INTRINSIC_WO_CHAIN || 4263 Opcode == ISD::INTRINSIC_W_CHAIN || 4264 Opcode == ISD::INTRINSIC_VOID) { 4265 unsigned NumBits = 4266 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4267 if (NumBits > 1) 4268 FirstAnswer = std::max(FirstAnswer, NumBits); 4269 } 4270 4271 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4272 // use this information. 4273 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4274 4275 APInt Mask; 4276 if (Known.isNonNegative()) { // sign bit is 0 4277 Mask = Known.Zero; 4278 } else if (Known.isNegative()) { // sign bit is 1; 4279 Mask = Known.One; 4280 } else { 4281 // Nothing known. 4282 return FirstAnswer; 4283 } 4284 4285 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4286 // the number of identical bits in the top of the input value. 4287 Mask <<= Mask.getBitWidth()-VTBits; 4288 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4289 } 4290 4291 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const { 4292 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4293 return Op.getScalarValueSizeInBits() - SignBits + 1; 4294 } 4295 4296 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, 4297 const APInt &DemandedElts, 4298 unsigned Depth) const { 4299 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4300 return Op.getScalarValueSizeInBits() - SignBits + 1; 4301 } 4302 4303 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4304 unsigned Depth) const { 4305 // Early out for FREEZE. 4306 if (Op.getOpcode() == ISD::FREEZE) 4307 return true; 4308 4309 // TODO: Assume we don't know anything for now. 4310 EVT VT = Op.getValueType(); 4311 if (VT.isScalableVector()) 4312 return false; 4313 4314 APInt DemandedElts = VT.isVector() 4315 ? APInt::getAllOnes(VT.getVectorNumElements()) 4316 : APInt(1, 1); 4317 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4318 } 4319 4320 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4321 const APInt &DemandedElts, 4322 bool PoisonOnly, 4323 unsigned Depth) const { 4324 unsigned Opcode = Op.getOpcode(); 4325 4326 // Early out for FREEZE. 4327 if (Opcode == ISD::FREEZE) 4328 return true; 4329 4330 if (Depth >= MaxRecursionDepth) 4331 return false; // Limit search depth. 4332 4333 if (isIntOrFPConstant(Op)) 4334 return true; 4335 4336 switch (Opcode) { 4337 case ISD::UNDEF: 4338 return PoisonOnly; 4339 4340 case ISD::BUILD_VECTOR: 4341 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4342 // this shouldn't affect the result. 4343 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4344 if (!DemandedElts[i]) 4345 continue; 4346 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4347 Depth + 1)) 4348 return false; 4349 } 4350 return true; 4351 4352 // TODO: Search for noundef attributes from library functions. 4353 4354 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4355 4356 default: 4357 // Allow the target to implement this method for its nodes. 4358 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4359 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4360 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4361 Op, DemandedElts, *this, PoisonOnly, Depth); 4362 break; 4363 } 4364 4365 return false; 4366 } 4367 4368 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4369 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4370 !isa<ConstantSDNode>(Op.getOperand(1))) 4371 return false; 4372 4373 if (Op.getOpcode() == ISD::OR && 4374 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4375 return false; 4376 4377 return true; 4378 } 4379 4380 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4381 // If we're told that NaNs won't happen, assume they won't. 4382 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4383 return true; 4384 4385 if (Depth >= MaxRecursionDepth) 4386 return false; // Limit search depth. 4387 4388 // TODO: Handle vectors. 4389 // If the value is a constant, we can obviously see if it is a NaN or not. 4390 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4391 return !C->getValueAPF().isNaN() || 4392 (SNaN && !C->getValueAPF().isSignaling()); 4393 } 4394 4395 unsigned Opcode = Op.getOpcode(); 4396 switch (Opcode) { 4397 case ISD::FADD: 4398 case ISD::FSUB: 4399 case ISD::FMUL: 4400 case ISD::FDIV: 4401 case ISD::FREM: 4402 case ISD::FSIN: 4403 case ISD::FCOS: { 4404 if (SNaN) 4405 return true; 4406 // TODO: Need isKnownNeverInfinity 4407 return false; 4408 } 4409 case ISD::FCANONICALIZE: 4410 case ISD::FEXP: 4411 case ISD::FEXP2: 4412 case ISD::FTRUNC: 4413 case ISD::FFLOOR: 4414 case ISD::FCEIL: 4415 case ISD::FROUND: 4416 case ISD::FROUNDEVEN: 4417 case ISD::FRINT: 4418 case ISD::FNEARBYINT: { 4419 if (SNaN) 4420 return true; 4421 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4422 } 4423 case ISD::FABS: 4424 case ISD::FNEG: 4425 case ISD::FCOPYSIGN: { 4426 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4427 } 4428 case ISD::SELECT: 4429 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4430 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4431 case ISD::FP_EXTEND: 4432 case ISD::FP_ROUND: { 4433 if (SNaN) 4434 return true; 4435 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4436 } 4437 case ISD::SINT_TO_FP: 4438 case ISD::UINT_TO_FP: 4439 return true; 4440 case ISD::FMA: 4441 case ISD::FMAD: { 4442 if (SNaN) 4443 return true; 4444 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4445 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4446 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4447 } 4448 case ISD::FSQRT: // Need is known positive 4449 case ISD::FLOG: 4450 case ISD::FLOG2: 4451 case ISD::FLOG10: 4452 case ISD::FPOWI: 4453 case ISD::FPOW: { 4454 if (SNaN) 4455 return true; 4456 // TODO: Refine on operand 4457 return false; 4458 } 4459 case ISD::FMINNUM: 4460 case ISD::FMAXNUM: { 4461 // Only one needs to be known not-nan, since it will be returned if the 4462 // other ends up being one. 4463 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4464 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4465 } 4466 case ISD::FMINNUM_IEEE: 4467 case ISD::FMAXNUM_IEEE: { 4468 if (SNaN) 4469 return true; 4470 // This can return a NaN if either operand is an sNaN, or if both operands 4471 // are NaN. 4472 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4473 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4474 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4475 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4476 } 4477 case ISD::FMINIMUM: 4478 case ISD::FMAXIMUM: { 4479 // TODO: Does this quiet or return the origina NaN as-is? 4480 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4481 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4482 } 4483 case ISD::EXTRACT_VECTOR_ELT: { 4484 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4485 } 4486 default: 4487 if (Opcode >= ISD::BUILTIN_OP_END || 4488 Opcode == ISD::INTRINSIC_WO_CHAIN || 4489 Opcode == ISD::INTRINSIC_W_CHAIN || 4490 Opcode == ISD::INTRINSIC_VOID) { 4491 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4492 } 4493 4494 return false; 4495 } 4496 } 4497 4498 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4499 assert(Op.getValueType().isFloatingPoint() && 4500 "Floating point type expected"); 4501 4502 // If the value is a constant, we can obviously see if it is a zero or not. 4503 // TODO: Add BuildVector support. 4504 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4505 return !C->isZero(); 4506 return false; 4507 } 4508 4509 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4510 assert(!Op.getValueType().isFloatingPoint() && 4511 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4512 4513 // If the value is a constant, we can obviously see if it is a zero or not. 4514 if (ISD::matchUnaryPredicate(Op, 4515 [](ConstantSDNode *C) { return !C->isZero(); })) 4516 return true; 4517 4518 // TODO: Recognize more cases here. 4519 switch (Op.getOpcode()) { 4520 default: break; 4521 case ISD::OR: 4522 if (isKnownNeverZero(Op.getOperand(1)) || 4523 isKnownNeverZero(Op.getOperand(0))) 4524 return true; 4525 break; 4526 } 4527 4528 return false; 4529 } 4530 4531 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4532 // Check the obvious case. 4533 if (A == B) return true; 4534 4535 // For for negative and positive zero. 4536 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4537 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4538 if (CA->isZero() && CB->isZero()) return true; 4539 4540 // Otherwise they may not be equal. 4541 return false; 4542 } 4543 4544 // FIXME: unify with llvm::haveNoCommonBitsSet. 4545 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4546 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4547 assert(A.getValueType() == B.getValueType() && 4548 "Values must have the same type"); 4549 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4550 computeKnownBits(B)); 4551 } 4552 4553 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4554 SelectionDAG &DAG) { 4555 if (cast<ConstantSDNode>(Step)->isZero()) 4556 return DAG.getConstant(0, DL, VT); 4557 4558 return SDValue(); 4559 } 4560 4561 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4562 ArrayRef<SDValue> Ops, 4563 SelectionDAG &DAG) { 4564 int NumOps = Ops.size(); 4565 assert(NumOps != 0 && "Can't build an empty vector!"); 4566 assert(!VT.isScalableVector() && 4567 "BUILD_VECTOR cannot be used with scalable types"); 4568 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4569 "Incorrect element count in BUILD_VECTOR!"); 4570 4571 // BUILD_VECTOR of UNDEFs is UNDEF. 4572 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4573 return DAG.getUNDEF(VT); 4574 4575 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4576 SDValue IdentitySrc; 4577 bool IsIdentity = true; 4578 for (int i = 0; i != NumOps; ++i) { 4579 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4580 Ops[i].getOperand(0).getValueType() != VT || 4581 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4582 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4583 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4584 IsIdentity = false; 4585 break; 4586 } 4587 IdentitySrc = Ops[i].getOperand(0); 4588 } 4589 if (IsIdentity) 4590 return IdentitySrc; 4591 4592 return SDValue(); 4593 } 4594 4595 /// Try to simplify vector concatenation to an input value, undef, or build 4596 /// vector. 4597 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4598 ArrayRef<SDValue> Ops, 4599 SelectionDAG &DAG) { 4600 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4601 assert(llvm::all_of(Ops, 4602 [Ops](SDValue Op) { 4603 return Ops[0].getValueType() == Op.getValueType(); 4604 }) && 4605 "Concatenation of vectors with inconsistent value types!"); 4606 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4607 VT.getVectorElementCount() && 4608 "Incorrect element count in vector concatenation!"); 4609 4610 if (Ops.size() == 1) 4611 return Ops[0]; 4612 4613 // Concat of UNDEFs is UNDEF. 4614 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4615 return DAG.getUNDEF(VT); 4616 4617 // Scan the operands and look for extract operations from a single source 4618 // that correspond to insertion at the same location via this concatenation: 4619 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4620 SDValue IdentitySrc; 4621 bool IsIdentity = true; 4622 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4623 SDValue Op = Ops[i]; 4624 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4625 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4626 Op.getOperand(0).getValueType() != VT || 4627 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4628 Op.getConstantOperandVal(1) != IdentityIndex) { 4629 IsIdentity = false; 4630 break; 4631 } 4632 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4633 "Unexpected identity source vector for concat of extracts"); 4634 IdentitySrc = Op.getOperand(0); 4635 } 4636 if (IsIdentity) { 4637 assert(IdentitySrc && "Failed to set source vector of extracts"); 4638 return IdentitySrc; 4639 } 4640 4641 // The code below this point is only designed to work for fixed width 4642 // vectors, so we bail out for now. 4643 if (VT.isScalableVector()) 4644 return SDValue(); 4645 4646 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4647 // simplified to one big BUILD_VECTOR. 4648 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4649 EVT SVT = VT.getScalarType(); 4650 SmallVector<SDValue, 16> Elts; 4651 for (SDValue Op : Ops) { 4652 EVT OpVT = Op.getValueType(); 4653 if (Op.isUndef()) 4654 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4655 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4656 Elts.append(Op->op_begin(), Op->op_end()); 4657 else 4658 return SDValue(); 4659 } 4660 4661 // BUILD_VECTOR requires all inputs to be of the same type, find the 4662 // maximum type and extend them all. 4663 for (SDValue Op : Elts) 4664 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4665 4666 if (SVT.bitsGT(VT.getScalarType())) { 4667 for (SDValue &Op : Elts) { 4668 if (Op.isUndef()) 4669 Op = DAG.getUNDEF(SVT); 4670 else 4671 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4672 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4673 : DAG.getSExtOrTrunc(Op, DL, SVT); 4674 } 4675 } 4676 4677 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4678 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4679 return V; 4680 } 4681 4682 /// Gets or creates the specified node. 4683 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4684 FoldingSetNodeID ID; 4685 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4686 void *IP = nullptr; 4687 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4688 return SDValue(E, 0); 4689 4690 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4691 getVTList(VT)); 4692 CSEMap.InsertNode(N, IP); 4693 4694 InsertNode(N); 4695 SDValue V = SDValue(N, 0); 4696 NewSDValueDbgMsg(V, "Creating new node: ", this); 4697 return V; 4698 } 4699 4700 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4701 SDValue Operand) { 4702 SDNodeFlags Flags; 4703 if (Inserter) 4704 Flags = Inserter->getFlags(); 4705 return getNode(Opcode, DL, VT, Operand, Flags); 4706 } 4707 4708 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4709 SDValue Operand, const SDNodeFlags Flags) { 4710 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4711 "Operand is DELETED_NODE!"); 4712 // Constant fold unary operations with an integer constant operand. Even 4713 // opaque constant will be folded, because the folding of unary operations 4714 // doesn't create new constants with different values. Nevertheless, the 4715 // opaque flag is preserved during folding to prevent future folding with 4716 // other constants. 4717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4718 const APInt &Val = C->getAPIntValue(); 4719 switch (Opcode) { 4720 default: break; 4721 case ISD::SIGN_EXTEND: 4722 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4723 C->isTargetOpcode(), C->isOpaque()); 4724 case ISD::TRUNCATE: 4725 if (C->isOpaque()) 4726 break; 4727 LLVM_FALLTHROUGH; 4728 case ISD::ZERO_EXTEND: 4729 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4730 C->isTargetOpcode(), C->isOpaque()); 4731 case ISD::ANY_EXTEND: 4732 // Some targets like RISCV prefer to sign extend some types. 4733 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4734 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4735 C->isTargetOpcode(), C->isOpaque()); 4736 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4737 C->isTargetOpcode(), C->isOpaque()); 4738 case ISD::UINT_TO_FP: 4739 case ISD::SINT_TO_FP: { 4740 APFloat apf(EVTToAPFloatSemantics(VT), 4741 APInt::getZero(VT.getSizeInBits())); 4742 (void)apf.convertFromAPInt(Val, 4743 Opcode==ISD::SINT_TO_FP, 4744 APFloat::rmNearestTiesToEven); 4745 return getConstantFP(apf, DL, VT); 4746 } 4747 case ISD::BITCAST: 4748 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4749 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4750 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4751 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4752 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4753 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4754 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4755 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4756 break; 4757 case ISD::ABS: 4758 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4759 C->isOpaque()); 4760 case ISD::BITREVERSE: 4761 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4762 C->isOpaque()); 4763 case ISD::BSWAP: 4764 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4765 C->isOpaque()); 4766 case ISD::CTPOP: 4767 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4768 C->isOpaque()); 4769 case ISD::CTLZ: 4770 case ISD::CTLZ_ZERO_UNDEF: 4771 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4772 C->isOpaque()); 4773 case ISD::CTTZ: 4774 case ISD::CTTZ_ZERO_UNDEF: 4775 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4776 C->isOpaque()); 4777 case ISD::FP16_TO_FP: { 4778 bool Ignored; 4779 APFloat FPV(APFloat::IEEEhalf(), 4780 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4781 4782 // This can return overflow, underflow, or inexact; we don't care. 4783 // FIXME need to be more flexible about rounding mode. 4784 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4785 APFloat::rmNearestTiesToEven, &Ignored); 4786 return getConstantFP(FPV, DL, VT); 4787 } 4788 case ISD::STEP_VECTOR: { 4789 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4790 return V; 4791 break; 4792 } 4793 } 4794 } 4795 4796 // Constant fold unary operations with a floating point constant operand. 4797 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4798 APFloat V = C->getValueAPF(); // make copy 4799 switch (Opcode) { 4800 case ISD::FNEG: 4801 V.changeSign(); 4802 return getConstantFP(V, DL, VT); 4803 case ISD::FABS: 4804 V.clearSign(); 4805 return getConstantFP(V, DL, VT); 4806 case ISD::FCEIL: { 4807 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4808 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4809 return getConstantFP(V, DL, VT); 4810 break; 4811 } 4812 case ISD::FTRUNC: { 4813 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4814 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4815 return getConstantFP(V, DL, VT); 4816 break; 4817 } 4818 case ISD::FFLOOR: { 4819 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4820 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4821 return getConstantFP(V, DL, VT); 4822 break; 4823 } 4824 case ISD::FP_EXTEND: { 4825 bool ignored; 4826 // This can return overflow, underflow, or inexact; we don't care. 4827 // FIXME need to be more flexible about rounding mode. 4828 (void)V.convert(EVTToAPFloatSemantics(VT), 4829 APFloat::rmNearestTiesToEven, &ignored); 4830 return getConstantFP(V, DL, VT); 4831 } 4832 case ISD::FP_TO_SINT: 4833 case ISD::FP_TO_UINT: { 4834 bool ignored; 4835 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4836 // FIXME need to be more flexible about rounding mode. 4837 APFloat::opStatus s = 4838 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4839 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4840 break; 4841 return getConstant(IntVal, DL, VT); 4842 } 4843 case ISD::BITCAST: 4844 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4845 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4846 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4847 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4848 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4849 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4850 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4851 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4852 break; 4853 case ISD::FP_TO_FP16: { 4854 bool Ignored; 4855 // This can return overflow, underflow, or inexact; we don't care. 4856 // FIXME need to be more flexible about rounding mode. 4857 (void)V.convert(APFloat::IEEEhalf(), 4858 APFloat::rmNearestTiesToEven, &Ignored); 4859 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4860 } 4861 } 4862 } 4863 4864 // Constant fold unary operations with a vector integer or float operand. 4865 switch (Opcode) { 4866 default: 4867 // FIXME: Entirely reasonable to perform folding of other unary 4868 // operations here as the need arises. 4869 break; 4870 case ISD::FNEG: 4871 case ISD::FABS: 4872 case ISD::FCEIL: 4873 case ISD::FTRUNC: 4874 case ISD::FFLOOR: 4875 case ISD::FP_EXTEND: 4876 case ISD::FP_TO_SINT: 4877 case ISD::FP_TO_UINT: 4878 case ISD::TRUNCATE: 4879 case ISD::ANY_EXTEND: 4880 case ISD::ZERO_EXTEND: 4881 case ISD::SIGN_EXTEND: 4882 case ISD::UINT_TO_FP: 4883 case ISD::SINT_TO_FP: 4884 case ISD::ABS: 4885 case ISD::BITREVERSE: 4886 case ISD::BSWAP: 4887 case ISD::CTLZ: 4888 case ISD::CTLZ_ZERO_UNDEF: 4889 case ISD::CTTZ: 4890 case ISD::CTTZ_ZERO_UNDEF: 4891 case ISD::CTPOP: { 4892 SDValue Ops = {Operand}; 4893 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 4894 return Fold; 4895 } 4896 } 4897 4898 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4899 switch (Opcode) { 4900 case ISD::STEP_VECTOR: 4901 assert(VT.isScalableVector() && 4902 "STEP_VECTOR can only be used with scalable types"); 4903 assert(OpOpcode == ISD::TargetConstant && 4904 VT.getVectorElementType() == Operand.getValueType() && 4905 "Unexpected step operand"); 4906 break; 4907 case ISD::FREEZE: 4908 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4909 break; 4910 case ISD::TokenFactor: 4911 case ISD::MERGE_VALUES: 4912 case ISD::CONCAT_VECTORS: 4913 return Operand; // Factor, merge or concat of one node? No need. 4914 case ISD::BUILD_VECTOR: { 4915 // Attempt to simplify BUILD_VECTOR. 4916 SDValue Ops[] = {Operand}; 4917 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4918 return V; 4919 break; 4920 } 4921 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4922 case ISD::FP_EXTEND: 4923 assert(VT.isFloatingPoint() && 4924 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4925 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4926 assert((!VT.isVector() || 4927 VT.getVectorElementCount() == 4928 Operand.getValueType().getVectorElementCount()) && 4929 "Vector element count mismatch!"); 4930 assert(Operand.getValueType().bitsLT(VT) && 4931 "Invalid fpext node, dst < src!"); 4932 if (Operand.isUndef()) 4933 return getUNDEF(VT); 4934 break; 4935 case ISD::FP_TO_SINT: 4936 case ISD::FP_TO_UINT: 4937 if (Operand.isUndef()) 4938 return getUNDEF(VT); 4939 break; 4940 case ISD::SINT_TO_FP: 4941 case ISD::UINT_TO_FP: 4942 // [us]itofp(undef) = 0, because the result value is bounded. 4943 if (Operand.isUndef()) 4944 return getConstantFP(0.0, DL, VT); 4945 break; 4946 case ISD::SIGN_EXTEND: 4947 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4948 "Invalid SIGN_EXTEND!"); 4949 assert(VT.isVector() == Operand.getValueType().isVector() && 4950 "SIGN_EXTEND result type type should be vector iff the operand " 4951 "type is vector!"); 4952 if (Operand.getValueType() == VT) return Operand; // noop extension 4953 assert((!VT.isVector() || 4954 VT.getVectorElementCount() == 4955 Operand.getValueType().getVectorElementCount()) && 4956 "Vector element count mismatch!"); 4957 assert(Operand.getValueType().bitsLT(VT) && 4958 "Invalid sext node, dst < src!"); 4959 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4960 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4961 if (OpOpcode == ISD::UNDEF) 4962 // sext(undef) = 0, because the top bits will all be the same. 4963 return getConstant(0, DL, VT); 4964 break; 4965 case ISD::ZERO_EXTEND: 4966 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4967 "Invalid ZERO_EXTEND!"); 4968 assert(VT.isVector() == Operand.getValueType().isVector() && 4969 "ZERO_EXTEND result type type should be vector iff the operand " 4970 "type is vector!"); 4971 if (Operand.getValueType() == VT) return Operand; // noop extension 4972 assert((!VT.isVector() || 4973 VT.getVectorElementCount() == 4974 Operand.getValueType().getVectorElementCount()) && 4975 "Vector element count mismatch!"); 4976 assert(Operand.getValueType().bitsLT(VT) && 4977 "Invalid zext node, dst < src!"); 4978 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4979 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4980 if (OpOpcode == ISD::UNDEF) 4981 // zext(undef) = 0, because the top bits will be zero. 4982 return getConstant(0, DL, VT); 4983 break; 4984 case ISD::ANY_EXTEND: 4985 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4986 "Invalid ANY_EXTEND!"); 4987 assert(VT.isVector() == Operand.getValueType().isVector() && 4988 "ANY_EXTEND result type type should be vector iff the operand " 4989 "type is vector!"); 4990 if (Operand.getValueType() == VT) return Operand; // noop extension 4991 assert((!VT.isVector() || 4992 VT.getVectorElementCount() == 4993 Operand.getValueType().getVectorElementCount()) && 4994 "Vector element count mismatch!"); 4995 assert(Operand.getValueType().bitsLT(VT) && 4996 "Invalid anyext node, dst < src!"); 4997 4998 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4999 OpOpcode == ISD::ANY_EXTEND) 5000 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5001 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5002 if (OpOpcode == ISD::UNDEF) 5003 return getUNDEF(VT); 5004 5005 // (ext (trunc x)) -> x 5006 if (OpOpcode == ISD::TRUNCATE) { 5007 SDValue OpOp = Operand.getOperand(0); 5008 if (OpOp.getValueType() == VT) { 5009 transferDbgValues(Operand, OpOp); 5010 return OpOp; 5011 } 5012 } 5013 break; 5014 case ISD::TRUNCATE: 5015 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5016 "Invalid TRUNCATE!"); 5017 assert(VT.isVector() == Operand.getValueType().isVector() && 5018 "TRUNCATE result type type should be vector iff the operand " 5019 "type is vector!"); 5020 if (Operand.getValueType() == VT) return Operand; // noop truncate 5021 assert((!VT.isVector() || 5022 VT.getVectorElementCount() == 5023 Operand.getValueType().getVectorElementCount()) && 5024 "Vector element count mismatch!"); 5025 assert(Operand.getValueType().bitsGT(VT) && 5026 "Invalid truncate node, src < dst!"); 5027 if (OpOpcode == ISD::TRUNCATE) 5028 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5029 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5030 OpOpcode == ISD::ANY_EXTEND) { 5031 // If the source is smaller than the dest, we still need an extend. 5032 if (Operand.getOperand(0).getValueType().getScalarType() 5033 .bitsLT(VT.getScalarType())) 5034 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5035 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5036 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5037 return Operand.getOperand(0); 5038 } 5039 if (OpOpcode == ISD::UNDEF) 5040 return getUNDEF(VT); 5041 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5042 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5043 break; 5044 case ISD::ANY_EXTEND_VECTOR_INREG: 5045 case ISD::ZERO_EXTEND_VECTOR_INREG: 5046 case ISD::SIGN_EXTEND_VECTOR_INREG: 5047 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5048 assert(Operand.getValueType().bitsLE(VT) && 5049 "The input must be the same size or smaller than the result."); 5050 assert(VT.getVectorMinNumElements() < 5051 Operand.getValueType().getVectorMinNumElements() && 5052 "The destination vector type must have fewer lanes than the input."); 5053 break; 5054 case ISD::ABS: 5055 assert(VT.isInteger() && VT == Operand.getValueType() && 5056 "Invalid ABS!"); 5057 if (OpOpcode == ISD::UNDEF) 5058 return getUNDEF(VT); 5059 break; 5060 case ISD::BSWAP: 5061 assert(VT.isInteger() && VT == Operand.getValueType() && 5062 "Invalid BSWAP!"); 5063 assert((VT.getScalarSizeInBits() % 16 == 0) && 5064 "BSWAP types must be a multiple of 16 bits!"); 5065 if (OpOpcode == ISD::UNDEF) 5066 return getUNDEF(VT); 5067 break; 5068 case ISD::BITREVERSE: 5069 assert(VT.isInteger() && VT == Operand.getValueType() && 5070 "Invalid BITREVERSE!"); 5071 if (OpOpcode == ISD::UNDEF) 5072 return getUNDEF(VT); 5073 break; 5074 case ISD::BITCAST: 5075 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5076 "Cannot BITCAST between types of different sizes!"); 5077 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5078 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5079 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5080 if (OpOpcode == ISD::UNDEF) 5081 return getUNDEF(VT); 5082 break; 5083 case ISD::SCALAR_TO_VECTOR: 5084 assert(VT.isVector() && !Operand.getValueType().isVector() && 5085 (VT.getVectorElementType() == Operand.getValueType() || 5086 (VT.getVectorElementType().isInteger() && 5087 Operand.getValueType().isInteger() && 5088 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5089 "Illegal SCALAR_TO_VECTOR node!"); 5090 if (OpOpcode == ISD::UNDEF) 5091 return getUNDEF(VT); 5092 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5093 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5094 isa<ConstantSDNode>(Operand.getOperand(1)) && 5095 Operand.getConstantOperandVal(1) == 0 && 5096 Operand.getOperand(0).getValueType() == VT) 5097 return Operand.getOperand(0); 5098 break; 5099 case ISD::FNEG: 5100 // Negation of an unknown bag of bits is still completely undefined. 5101 if (OpOpcode == ISD::UNDEF) 5102 return getUNDEF(VT); 5103 5104 if (OpOpcode == ISD::FNEG) // --X -> X 5105 return Operand.getOperand(0); 5106 break; 5107 case ISD::FABS: 5108 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5109 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5110 break; 5111 case ISD::VSCALE: 5112 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5113 break; 5114 case ISD::CTPOP: 5115 if (Operand.getValueType().getScalarType() == MVT::i1) 5116 return Operand; 5117 break; 5118 case ISD::CTLZ: 5119 case ISD::CTTZ: 5120 if (Operand.getValueType().getScalarType() == MVT::i1) 5121 return getNOT(DL, Operand, Operand.getValueType()); 5122 break; 5123 case ISD::VECREDUCE_SMIN: 5124 case ISD::VECREDUCE_UMAX: 5125 if (Operand.getValueType().getScalarType() == MVT::i1) 5126 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5127 break; 5128 case ISD::VECREDUCE_SMAX: 5129 case ISD::VECREDUCE_UMIN: 5130 if (Operand.getValueType().getScalarType() == MVT::i1) 5131 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5132 break; 5133 } 5134 5135 SDNode *N; 5136 SDVTList VTs = getVTList(VT); 5137 SDValue Ops[] = {Operand}; 5138 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5139 FoldingSetNodeID ID; 5140 AddNodeIDNode(ID, Opcode, VTs, Ops); 5141 void *IP = nullptr; 5142 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5143 E->intersectFlagsWith(Flags); 5144 return SDValue(E, 0); 5145 } 5146 5147 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5148 N->setFlags(Flags); 5149 createOperands(N, Ops); 5150 CSEMap.InsertNode(N, IP); 5151 } else { 5152 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5153 createOperands(N, Ops); 5154 } 5155 5156 InsertNode(N); 5157 SDValue V = SDValue(N, 0); 5158 NewSDValueDbgMsg(V, "Creating new node: ", this); 5159 return V; 5160 } 5161 5162 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5163 const APInt &C2) { 5164 switch (Opcode) { 5165 case ISD::ADD: return C1 + C2; 5166 case ISD::SUB: return C1 - C2; 5167 case ISD::MUL: return C1 * C2; 5168 case ISD::AND: return C1 & C2; 5169 case ISD::OR: return C1 | C2; 5170 case ISD::XOR: return C1 ^ C2; 5171 case ISD::SHL: return C1 << C2; 5172 case ISD::SRL: return C1.lshr(C2); 5173 case ISD::SRA: return C1.ashr(C2); 5174 case ISD::ROTL: return C1.rotl(C2); 5175 case ISD::ROTR: return C1.rotr(C2); 5176 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5177 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5178 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5179 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5180 case ISD::SADDSAT: return C1.sadd_sat(C2); 5181 case ISD::UADDSAT: return C1.uadd_sat(C2); 5182 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5183 case ISD::USUBSAT: return C1.usub_sat(C2); 5184 case ISD::UDIV: 5185 if (!C2.getBoolValue()) 5186 break; 5187 return C1.udiv(C2); 5188 case ISD::UREM: 5189 if (!C2.getBoolValue()) 5190 break; 5191 return C1.urem(C2); 5192 case ISD::SDIV: 5193 if (!C2.getBoolValue()) 5194 break; 5195 return C1.sdiv(C2); 5196 case ISD::SREM: 5197 if (!C2.getBoolValue()) 5198 break; 5199 return C1.srem(C2); 5200 case ISD::MULHS: { 5201 unsigned FullWidth = C1.getBitWidth() * 2; 5202 APInt C1Ext = C1.sext(FullWidth); 5203 APInt C2Ext = C2.sext(FullWidth); 5204 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5205 } 5206 case ISD::MULHU: { 5207 unsigned FullWidth = C1.getBitWidth() * 2; 5208 APInt C1Ext = C1.zext(FullWidth); 5209 APInt C2Ext = C2.zext(FullWidth); 5210 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5211 } 5212 } 5213 return llvm::None; 5214 } 5215 5216 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5217 const GlobalAddressSDNode *GA, 5218 const SDNode *N2) { 5219 if (GA->getOpcode() != ISD::GlobalAddress) 5220 return SDValue(); 5221 if (!TLI->isOffsetFoldingLegal(GA)) 5222 return SDValue(); 5223 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5224 if (!C2) 5225 return SDValue(); 5226 int64_t Offset = C2->getSExtValue(); 5227 switch (Opcode) { 5228 case ISD::ADD: break; 5229 case ISD::SUB: Offset = -uint64_t(Offset); break; 5230 default: return SDValue(); 5231 } 5232 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5233 GA->getOffset() + uint64_t(Offset)); 5234 } 5235 5236 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5237 switch (Opcode) { 5238 case ISD::SDIV: 5239 case ISD::UDIV: 5240 case ISD::SREM: 5241 case ISD::UREM: { 5242 // If a divisor is zero/undef or any element of a divisor vector is 5243 // zero/undef, the whole op is undef. 5244 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5245 SDValue Divisor = Ops[1]; 5246 if (Divisor.isUndef() || isNullConstant(Divisor)) 5247 return true; 5248 5249 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5250 llvm::any_of(Divisor->op_values(), 5251 [](SDValue V) { return V.isUndef() || 5252 isNullConstant(V); }); 5253 // TODO: Handle signed overflow. 5254 } 5255 // TODO: Handle oversized shifts. 5256 default: 5257 return false; 5258 } 5259 } 5260 5261 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5262 EVT VT, ArrayRef<SDValue> Ops) { 5263 // If the opcode is a target-specific ISD node, there's nothing we can 5264 // do here and the operand rules may not line up with the below, so 5265 // bail early. 5266 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5267 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5268 // foldCONCAT_VECTORS in getNode before this is called. 5269 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5270 return SDValue(); 5271 5272 unsigned NumOps = Ops.size(); 5273 if (NumOps == 0) 5274 return SDValue(); 5275 5276 if (isUndef(Opcode, Ops)) 5277 return getUNDEF(VT); 5278 5279 // Handle the case of two scalars. 5280 if (NumOps == 2) { 5281 // TODO: Move foldConstantFPMath here? 5282 5283 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5284 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5285 if (C1->isOpaque() || C2->isOpaque()) 5286 return SDValue(); 5287 5288 Optional<APInt> FoldAttempt = 5289 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5290 if (!FoldAttempt) 5291 return SDValue(); 5292 5293 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5294 assert((!Folded || !VT.isVector()) && 5295 "Can't fold vectors ops with scalar operands"); 5296 return Folded; 5297 } 5298 } 5299 5300 // fold (add Sym, c) -> Sym+c 5301 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5302 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5303 if (TLI->isCommutativeBinOp(Opcode)) 5304 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5305 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5306 } 5307 5308 // This is for vector folding only from here on. 5309 if (!VT.isVector()) 5310 return SDValue(); 5311 5312 ElementCount NumElts = VT.getVectorElementCount(); 5313 5314 // See if we can fold through bitcasted integer ops. 5315 // TODO: Can we handle undef elements? 5316 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5317 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5318 Ops[0].getOpcode() == ISD::BITCAST && 5319 Ops[1].getOpcode() == ISD::BITCAST) { 5320 SDValue N1 = peekThroughBitcasts(Ops[0]); 5321 SDValue N2 = peekThroughBitcasts(Ops[1]); 5322 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5323 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5324 EVT BVVT = N1.getValueType(); 5325 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5326 bool IsLE = getDataLayout().isLittleEndian(); 5327 unsigned EltBits = VT.getScalarSizeInBits(); 5328 SmallVector<APInt> RawBits1, RawBits2; 5329 BitVector UndefElts1, UndefElts2; 5330 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5331 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5332 UndefElts1.none() && UndefElts2.none()) { 5333 SmallVector<APInt> RawBits; 5334 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5335 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5336 if (!Fold) 5337 break; 5338 RawBits.push_back(Fold.getValue()); 5339 } 5340 if (RawBits.size() == NumElts.getFixedValue()) { 5341 // We have constant folded, but we need to cast this again back to 5342 // the original (possibly legalized) type. 5343 SmallVector<APInt> DstBits; 5344 BitVector DstUndefs; 5345 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5346 DstBits, RawBits, DstUndefs, 5347 BitVector(RawBits.size(), false)); 5348 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5349 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5350 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5351 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5352 if (DstUndefs[I]) 5353 continue; 5354 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5355 } 5356 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5357 } 5358 } 5359 } 5360 } 5361 5362 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5363 return !Op.getValueType().isVector() || 5364 Op.getValueType().getVectorElementCount() == NumElts; 5365 }; 5366 5367 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5368 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5369 Op.getOpcode() == ISD::BUILD_VECTOR || 5370 Op.getOpcode() == ISD::SPLAT_VECTOR; 5371 }; 5372 5373 // All operands must be vector types with the same number of elements as 5374 // the result type and must be either UNDEF or a build/splat vector 5375 // or UNDEF scalars. 5376 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5377 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5378 return SDValue(); 5379 5380 // If we are comparing vectors, then the result needs to be a i1 boolean 5381 // that is then sign-extended back to the legal result type. 5382 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5383 5384 // Find legal integer scalar type for constant promotion and 5385 // ensure that its scalar size is at least as large as source. 5386 EVT LegalSVT = VT.getScalarType(); 5387 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5388 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5389 if (LegalSVT.bitsLT(VT.getScalarType())) 5390 return SDValue(); 5391 } 5392 5393 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5394 // only have one operand to check. For fixed-length vector types we may have 5395 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5396 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5397 5398 // Constant fold each scalar lane separately. 5399 SmallVector<SDValue, 4> ScalarResults; 5400 for (unsigned I = 0; I != NumVectorElts; I++) { 5401 SmallVector<SDValue, 4> ScalarOps; 5402 for (SDValue Op : Ops) { 5403 EVT InSVT = Op.getValueType().getScalarType(); 5404 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5405 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5406 if (Op.isUndef()) 5407 ScalarOps.push_back(getUNDEF(InSVT)); 5408 else 5409 ScalarOps.push_back(Op); 5410 continue; 5411 } 5412 5413 SDValue ScalarOp = 5414 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5415 EVT ScalarVT = ScalarOp.getValueType(); 5416 5417 // Build vector (integer) scalar operands may need implicit 5418 // truncation - do this before constant folding. 5419 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5420 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5421 5422 ScalarOps.push_back(ScalarOp); 5423 } 5424 5425 // Constant fold the scalar operands. 5426 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5427 5428 // Legalize the (integer) scalar constant if necessary. 5429 if (LegalSVT != SVT) 5430 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5431 5432 // Scalar folding only succeeded if the result is a constant or UNDEF. 5433 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5434 ScalarResult.getOpcode() != ISD::ConstantFP) 5435 return SDValue(); 5436 ScalarResults.push_back(ScalarResult); 5437 } 5438 5439 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5440 : getBuildVector(VT, DL, ScalarResults); 5441 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5442 return V; 5443 } 5444 5445 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5446 EVT VT, SDValue N1, SDValue N2) { 5447 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5448 // should. That will require dealing with a potentially non-default 5449 // rounding mode, checking the "opStatus" return value from the APFloat 5450 // math calculations, and possibly other variations. 5451 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5452 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5453 if (N1CFP && N2CFP) { 5454 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5455 switch (Opcode) { 5456 case ISD::FADD: 5457 C1.add(C2, APFloat::rmNearestTiesToEven); 5458 return getConstantFP(C1, DL, VT); 5459 case ISD::FSUB: 5460 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5461 return getConstantFP(C1, DL, VT); 5462 case ISD::FMUL: 5463 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5464 return getConstantFP(C1, DL, VT); 5465 case ISD::FDIV: 5466 C1.divide(C2, APFloat::rmNearestTiesToEven); 5467 return getConstantFP(C1, DL, VT); 5468 case ISD::FREM: 5469 C1.mod(C2); 5470 return getConstantFP(C1, DL, VT); 5471 case ISD::FCOPYSIGN: 5472 C1.copySign(C2); 5473 return getConstantFP(C1, DL, VT); 5474 default: break; 5475 } 5476 } 5477 if (N1CFP && Opcode == ISD::FP_ROUND) { 5478 APFloat C1 = N1CFP->getValueAPF(); // make copy 5479 bool Unused; 5480 // This can return overflow, underflow, or inexact; we don't care. 5481 // FIXME need to be more flexible about rounding mode. 5482 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5483 &Unused); 5484 return getConstantFP(C1, DL, VT); 5485 } 5486 5487 switch (Opcode) { 5488 case ISD::FSUB: 5489 // -0.0 - undef --> undef (consistent with "fneg undef") 5490 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5491 return getUNDEF(VT); 5492 LLVM_FALLTHROUGH; 5493 5494 case ISD::FADD: 5495 case ISD::FMUL: 5496 case ISD::FDIV: 5497 case ISD::FREM: 5498 // If both operands are undef, the result is undef. If 1 operand is undef, 5499 // the result is NaN. This should match the behavior of the IR optimizer. 5500 if (N1.isUndef() && N2.isUndef()) 5501 return getUNDEF(VT); 5502 if (N1.isUndef() || N2.isUndef()) 5503 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5504 } 5505 return SDValue(); 5506 } 5507 5508 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5509 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5510 5511 // There's no need to assert on a byte-aligned pointer. All pointers are at 5512 // least byte aligned. 5513 if (A == Align(1)) 5514 return Val; 5515 5516 FoldingSetNodeID ID; 5517 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5518 ID.AddInteger(A.value()); 5519 5520 void *IP = nullptr; 5521 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5522 return SDValue(E, 0); 5523 5524 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5525 Val.getValueType(), A); 5526 createOperands(N, {Val}); 5527 5528 CSEMap.InsertNode(N, IP); 5529 InsertNode(N); 5530 5531 SDValue V(N, 0); 5532 NewSDValueDbgMsg(V, "Creating new node: ", this); 5533 return V; 5534 } 5535 5536 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5537 SDValue N1, SDValue N2) { 5538 SDNodeFlags Flags; 5539 if (Inserter) 5540 Flags = Inserter->getFlags(); 5541 return getNode(Opcode, DL, VT, N1, N2, Flags); 5542 } 5543 5544 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5545 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5546 assert(N1.getOpcode() != ISD::DELETED_NODE && 5547 N2.getOpcode() != ISD::DELETED_NODE && 5548 "Operand is DELETED_NODE!"); 5549 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5550 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5551 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5552 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5553 5554 // Canonicalize constant to RHS if commutative. 5555 if (TLI->isCommutativeBinOp(Opcode)) { 5556 if (N1C && !N2C) { 5557 std::swap(N1C, N2C); 5558 std::swap(N1, N2); 5559 } else if (N1CFP && !N2CFP) { 5560 std::swap(N1CFP, N2CFP); 5561 std::swap(N1, N2); 5562 } 5563 } 5564 5565 switch (Opcode) { 5566 default: break; 5567 case ISD::TokenFactor: 5568 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5569 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5570 // Fold trivial token factors. 5571 if (N1.getOpcode() == ISD::EntryToken) return N2; 5572 if (N2.getOpcode() == ISD::EntryToken) return N1; 5573 if (N1 == N2) return N1; 5574 break; 5575 case ISD::BUILD_VECTOR: { 5576 // Attempt to simplify BUILD_VECTOR. 5577 SDValue Ops[] = {N1, N2}; 5578 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5579 return V; 5580 break; 5581 } 5582 case ISD::CONCAT_VECTORS: { 5583 SDValue Ops[] = {N1, N2}; 5584 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5585 return V; 5586 break; 5587 } 5588 case ISD::AND: 5589 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5590 assert(N1.getValueType() == N2.getValueType() && 5591 N1.getValueType() == VT && "Binary operator types must match!"); 5592 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5593 // worth handling here. 5594 if (N2C && N2C->isZero()) 5595 return N2; 5596 if (N2C && N2C->isAllOnes()) // X & -1 -> X 5597 return N1; 5598 break; 5599 case ISD::OR: 5600 case ISD::XOR: 5601 case ISD::ADD: 5602 case ISD::SUB: 5603 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5604 assert(N1.getValueType() == N2.getValueType() && 5605 N1.getValueType() == VT && "Binary operator types must match!"); 5606 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5607 // it's worth handling here. 5608 if (N2C && N2C->isZero()) 5609 return N1; 5610 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5611 VT.getVectorElementType() == MVT::i1) 5612 return getNode(ISD::XOR, DL, VT, N1, N2); 5613 break; 5614 case ISD::MUL: 5615 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5616 assert(N1.getValueType() == N2.getValueType() && 5617 N1.getValueType() == VT && "Binary operator types must match!"); 5618 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5619 return getNode(ISD::AND, DL, VT, N1, N2); 5620 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5621 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5622 const APInt &N2CImm = N2C->getAPIntValue(); 5623 return getVScale(DL, VT, MulImm * N2CImm); 5624 } 5625 break; 5626 case ISD::UDIV: 5627 case ISD::UREM: 5628 case ISD::MULHU: 5629 case ISD::MULHS: 5630 case ISD::SDIV: 5631 case ISD::SREM: 5632 case ISD::SADDSAT: 5633 case ISD::SSUBSAT: 5634 case ISD::UADDSAT: 5635 case ISD::USUBSAT: 5636 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5637 assert(N1.getValueType() == N2.getValueType() && 5638 N1.getValueType() == VT && "Binary operator types must match!"); 5639 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5640 // fold (add_sat x, y) -> (or x, y) for bool types. 5641 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5642 return getNode(ISD::OR, DL, VT, N1, N2); 5643 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5644 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5645 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5646 } 5647 break; 5648 case ISD::SMIN: 5649 case ISD::UMAX: 5650 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5651 assert(N1.getValueType() == N2.getValueType() && 5652 N1.getValueType() == VT && "Binary operator types must match!"); 5653 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5654 return getNode(ISD::OR, DL, VT, N1, N2); 5655 break; 5656 case ISD::SMAX: 5657 case ISD::UMIN: 5658 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5659 assert(N1.getValueType() == N2.getValueType() && 5660 N1.getValueType() == VT && "Binary operator types must match!"); 5661 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5662 return getNode(ISD::AND, DL, VT, N1, N2); 5663 break; 5664 case ISD::FADD: 5665 case ISD::FSUB: 5666 case ISD::FMUL: 5667 case ISD::FDIV: 5668 case ISD::FREM: 5669 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5670 assert(N1.getValueType() == N2.getValueType() && 5671 N1.getValueType() == VT && "Binary operator types must match!"); 5672 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5673 return V; 5674 break; 5675 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5676 assert(N1.getValueType() == VT && 5677 N1.getValueType().isFloatingPoint() && 5678 N2.getValueType().isFloatingPoint() && 5679 "Invalid FCOPYSIGN!"); 5680 break; 5681 case ISD::SHL: 5682 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5683 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5684 const APInt &ShiftImm = N2C->getAPIntValue(); 5685 return getVScale(DL, VT, MulImm << ShiftImm); 5686 } 5687 LLVM_FALLTHROUGH; 5688 case ISD::SRA: 5689 case ISD::SRL: 5690 if (SDValue V = simplifyShift(N1, N2)) 5691 return V; 5692 LLVM_FALLTHROUGH; 5693 case ISD::ROTL: 5694 case ISD::ROTR: 5695 assert(VT == N1.getValueType() && 5696 "Shift operators return type must be the same as their first arg"); 5697 assert(VT.isInteger() && N2.getValueType().isInteger() && 5698 "Shifts only work on integers"); 5699 assert((!VT.isVector() || VT == N2.getValueType()) && 5700 "Vector shift amounts must be in the same as their first arg"); 5701 // Verify that the shift amount VT is big enough to hold valid shift 5702 // amounts. This catches things like trying to shift an i1024 value by an 5703 // i8, which is easy to fall into in generic code that uses 5704 // TLI.getShiftAmount(). 5705 assert(N2.getValueType().getScalarSizeInBits() >= 5706 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5707 "Invalid use of small shift amount with oversized value!"); 5708 5709 // Always fold shifts of i1 values so the code generator doesn't need to 5710 // handle them. Since we know the size of the shift has to be less than the 5711 // size of the value, the shift/rotate count is guaranteed to be zero. 5712 if (VT == MVT::i1) 5713 return N1; 5714 if (N2C && N2C->isZero()) 5715 return N1; 5716 break; 5717 case ISD::FP_ROUND: 5718 assert(VT.isFloatingPoint() && 5719 N1.getValueType().isFloatingPoint() && 5720 VT.bitsLE(N1.getValueType()) && 5721 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5722 "Invalid FP_ROUND!"); 5723 if (N1.getValueType() == VT) return N1; // noop conversion. 5724 break; 5725 case ISD::AssertSext: 5726 case ISD::AssertZext: { 5727 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5728 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5729 assert(VT.isInteger() && EVT.isInteger() && 5730 "Cannot *_EXTEND_INREG FP types"); 5731 assert(!EVT.isVector() && 5732 "AssertSExt/AssertZExt type should be the vector element type " 5733 "rather than the vector type!"); 5734 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5735 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5736 break; 5737 } 5738 case ISD::SIGN_EXTEND_INREG: { 5739 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5740 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5741 assert(VT.isInteger() && EVT.isInteger() && 5742 "Cannot *_EXTEND_INREG FP types"); 5743 assert(EVT.isVector() == VT.isVector() && 5744 "SIGN_EXTEND_INREG type should be vector iff the operand " 5745 "type is vector!"); 5746 assert((!EVT.isVector() || 5747 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5748 "Vector element counts must match in SIGN_EXTEND_INREG"); 5749 assert(EVT.bitsLE(VT) && "Not extending!"); 5750 if (EVT == VT) return N1; // Not actually extending 5751 5752 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5753 unsigned FromBits = EVT.getScalarSizeInBits(); 5754 Val <<= Val.getBitWidth() - FromBits; 5755 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5756 return getConstant(Val, DL, ConstantVT); 5757 }; 5758 5759 if (N1C) { 5760 const APInt &Val = N1C->getAPIntValue(); 5761 return SignExtendInReg(Val, VT); 5762 } 5763 5764 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5765 SmallVector<SDValue, 8> Ops; 5766 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5767 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5768 SDValue Op = N1.getOperand(i); 5769 if (Op.isUndef()) { 5770 Ops.push_back(getUNDEF(OpVT)); 5771 continue; 5772 } 5773 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5774 APInt Val = C->getAPIntValue(); 5775 Ops.push_back(SignExtendInReg(Val, OpVT)); 5776 } 5777 return getBuildVector(VT, DL, Ops); 5778 } 5779 break; 5780 } 5781 case ISD::FP_TO_SINT_SAT: 5782 case ISD::FP_TO_UINT_SAT: { 5783 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5784 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5785 assert(N1.getValueType().isVector() == VT.isVector() && 5786 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5787 "vector!"); 5788 assert((!VT.isVector() || VT.getVectorNumElements() == 5789 N1.getValueType().getVectorNumElements()) && 5790 "Vector element counts must match in FP_TO_*INT_SAT"); 5791 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5792 "Type to saturate to must be a scalar."); 5793 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5794 "Not extending!"); 5795 break; 5796 } 5797 case ISD::EXTRACT_VECTOR_ELT: 5798 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5799 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5800 element type of the vector."); 5801 5802 // Extract from an undefined value or using an undefined index is undefined. 5803 if (N1.isUndef() || N2.isUndef()) 5804 return getUNDEF(VT); 5805 5806 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5807 // vectors. For scalable vectors we will provide appropriate support for 5808 // dealing with arbitrary indices. 5809 if (N2C && N1.getValueType().isFixedLengthVector() && 5810 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5811 return getUNDEF(VT); 5812 5813 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5814 // expanding copies of large vectors from registers. This only works for 5815 // fixed length vectors, since we need to know the exact number of 5816 // elements. 5817 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5818 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5819 unsigned Factor = 5820 N1.getOperand(0).getValueType().getVectorNumElements(); 5821 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5822 N1.getOperand(N2C->getZExtValue() / Factor), 5823 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5824 } 5825 5826 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5827 // lowering is expanding large vector constants. 5828 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5829 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5830 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5831 N1.getValueType().isFixedLengthVector()) && 5832 "BUILD_VECTOR used for scalable vectors"); 5833 unsigned Index = 5834 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5835 SDValue Elt = N1.getOperand(Index); 5836 5837 if (VT != Elt.getValueType()) 5838 // If the vector element type is not legal, the BUILD_VECTOR operands 5839 // are promoted and implicitly truncated, and the result implicitly 5840 // extended. Make that explicit here. 5841 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5842 5843 return Elt; 5844 } 5845 5846 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5847 // operations are lowered to scalars. 5848 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5849 // If the indices are the same, return the inserted element else 5850 // if the indices are known different, extract the element from 5851 // the original vector. 5852 SDValue N1Op2 = N1.getOperand(2); 5853 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5854 5855 if (N1Op2C && N2C) { 5856 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5857 if (VT == N1.getOperand(1).getValueType()) 5858 return N1.getOperand(1); 5859 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5860 } 5861 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5862 } 5863 } 5864 5865 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5866 // when vector types are scalarized and v1iX is legal. 5867 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5868 // Here we are completely ignoring the extract element index (N2), 5869 // which is fine for fixed width vectors, since any index other than 0 5870 // is undefined anyway. However, this cannot be ignored for scalable 5871 // vectors - in theory we could support this, but we don't want to do this 5872 // without a profitability check. 5873 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5874 N1.getValueType().isFixedLengthVector() && 5875 N1.getValueType().getVectorNumElements() == 1) { 5876 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5877 N1.getOperand(1)); 5878 } 5879 break; 5880 case ISD::EXTRACT_ELEMENT: 5881 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5882 assert(!N1.getValueType().isVector() && !VT.isVector() && 5883 (N1.getValueType().isInteger() == VT.isInteger()) && 5884 N1.getValueType() != VT && 5885 "Wrong types for EXTRACT_ELEMENT!"); 5886 5887 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5888 // 64-bit integers into 32-bit parts. Instead of building the extract of 5889 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5890 if (N1.getOpcode() == ISD::BUILD_PAIR) 5891 return N1.getOperand(N2C->getZExtValue()); 5892 5893 // EXTRACT_ELEMENT of a constant int is also very common. 5894 if (N1C) { 5895 unsigned ElementSize = VT.getSizeInBits(); 5896 unsigned Shift = ElementSize * N2C->getZExtValue(); 5897 const APInt &Val = N1C->getAPIntValue(); 5898 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5899 } 5900 break; 5901 case ISD::EXTRACT_SUBVECTOR: { 5902 EVT N1VT = N1.getValueType(); 5903 assert(VT.isVector() && N1VT.isVector() && 5904 "Extract subvector VTs must be vectors!"); 5905 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5906 "Extract subvector VTs must have the same element type!"); 5907 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5908 "Cannot extract a scalable vector from a fixed length vector!"); 5909 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5910 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5911 "Extract subvector must be from larger vector to smaller vector!"); 5912 assert(N2C && "Extract subvector index must be a constant"); 5913 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5914 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5915 N1VT.getVectorMinNumElements()) && 5916 "Extract subvector overflow!"); 5917 assert(N2C->getAPIntValue().getBitWidth() == 5918 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5919 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5920 5921 // Trivial extraction. 5922 if (VT == N1VT) 5923 return N1; 5924 5925 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5926 if (N1.isUndef()) 5927 return getUNDEF(VT); 5928 5929 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5930 // the concat have the same type as the extract. 5931 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5932 VT == N1.getOperand(0).getValueType()) { 5933 unsigned Factor = VT.getVectorMinNumElements(); 5934 return N1.getOperand(N2C->getZExtValue() / Factor); 5935 } 5936 5937 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5938 // during shuffle legalization. 5939 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5940 VT == N1.getOperand(1).getValueType()) 5941 return N1.getOperand(1); 5942 break; 5943 } 5944 } 5945 5946 // Perform trivial constant folding. 5947 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5948 return SV; 5949 5950 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5951 return V; 5952 5953 // Canonicalize an UNDEF to the RHS, even over a constant. 5954 if (N1.isUndef()) { 5955 if (TLI->isCommutativeBinOp(Opcode)) { 5956 std::swap(N1, N2); 5957 } else { 5958 switch (Opcode) { 5959 case ISD::SIGN_EXTEND_INREG: 5960 case ISD::SUB: 5961 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5962 case ISD::UDIV: 5963 case ISD::SDIV: 5964 case ISD::UREM: 5965 case ISD::SREM: 5966 case ISD::SSUBSAT: 5967 case ISD::USUBSAT: 5968 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5969 } 5970 } 5971 } 5972 5973 // Fold a bunch of operators when the RHS is undef. 5974 if (N2.isUndef()) { 5975 switch (Opcode) { 5976 case ISD::XOR: 5977 if (N1.isUndef()) 5978 // Handle undef ^ undef -> 0 special case. This is a common 5979 // idiom (misuse). 5980 return getConstant(0, DL, VT); 5981 LLVM_FALLTHROUGH; 5982 case ISD::ADD: 5983 case ISD::SUB: 5984 case ISD::UDIV: 5985 case ISD::SDIV: 5986 case ISD::UREM: 5987 case ISD::SREM: 5988 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5989 case ISD::MUL: 5990 case ISD::AND: 5991 case ISD::SSUBSAT: 5992 case ISD::USUBSAT: 5993 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5994 case ISD::OR: 5995 case ISD::SADDSAT: 5996 case ISD::UADDSAT: 5997 return getAllOnesConstant(DL, VT); 5998 } 5999 } 6000 6001 // Memoize this node if possible. 6002 SDNode *N; 6003 SDVTList VTs = getVTList(VT); 6004 SDValue Ops[] = {N1, N2}; 6005 if (VT != MVT::Glue) { 6006 FoldingSetNodeID ID; 6007 AddNodeIDNode(ID, Opcode, VTs, Ops); 6008 void *IP = nullptr; 6009 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6010 E->intersectFlagsWith(Flags); 6011 return SDValue(E, 0); 6012 } 6013 6014 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6015 N->setFlags(Flags); 6016 createOperands(N, Ops); 6017 CSEMap.InsertNode(N, IP); 6018 } else { 6019 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6020 createOperands(N, Ops); 6021 } 6022 6023 InsertNode(N); 6024 SDValue V = SDValue(N, 0); 6025 NewSDValueDbgMsg(V, "Creating new node: ", this); 6026 return V; 6027 } 6028 6029 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6030 SDValue N1, SDValue N2, SDValue N3) { 6031 SDNodeFlags Flags; 6032 if (Inserter) 6033 Flags = Inserter->getFlags(); 6034 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6035 } 6036 6037 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6038 SDValue N1, SDValue N2, SDValue N3, 6039 const SDNodeFlags Flags) { 6040 assert(N1.getOpcode() != ISD::DELETED_NODE && 6041 N2.getOpcode() != ISD::DELETED_NODE && 6042 N3.getOpcode() != ISD::DELETED_NODE && 6043 "Operand is DELETED_NODE!"); 6044 // Perform various simplifications. 6045 switch (Opcode) { 6046 case ISD::FMA: { 6047 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6048 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6049 N3.getValueType() == VT && "FMA types must match!"); 6050 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6051 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6052 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6053 if (N1CFP && N2CFP && N3CFP) { 6054 APFloat V1 = N1CFP->getValueAPF(); 6055 const APFloat &V2 = N2CFP->getValueAPF(); 6056 const APFloat &V3 = N3CFP->getValueAPF(); 6057 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6058 return getConstantFP(V1, DL, VT); 6059 } 6060 break; 6061 } 6062 case ISD::BUILD_VECTOR: { 6063 // Attempt to simplify BUILD_VECTOR. 6064 SDValue Ops[] = {N1, N2, N3}; 6065 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6066 return V; 6067 break; 6068 } 6069 case ISD::CONCAT_VECTORS: { 6070 SDValue Ops[] = {N1, N2, N3}; 6071 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6072 return V; 6073 break; 6074 } 6075 case ISD::SETCC: { 6076 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6077 assert(N1.getValueType() == N2.getValueType() && 6078 "SETCC operands must have the same type!"); 6079 assert(VT.isVector() == N1.getValueType().isVector() && 6080 "SETCC type should be vector iff the operand type is vector!"); 6081 assert((!VT.isVector() || VT.getVectorElementCount() == 6082 N1.getValueType().getVectorElementCount()) && 6083 "SETCC vector element counts must match!"); 6084 // Use FoldSetCC to simplify SETCC's. 6085 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6086 return V; 6087 // Vector constant folding. 6088 SDValue Ops[] = {N1, N2, N3}; 6089 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6090 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6091 return V; 6092 } 6093 break; 6094 } 6095 case ISD::SELECT: 6096 case ISD::VSELECT: 6097 if (SDValue V = simplifySelect(N1, N2, N3)) 6098 return V; 6099 break; 6100 case ISD::VECTOR_SHUFFLE: 6101 llvm_unreachable("should use getVectorShuffle constructor!"); 6102 case ISD::VECTOR_SPLICE: { 6103 if (cast<ConstantSDNode>(N3)->isNullValue()) 6104 return N1; 6105 break; 6106 } 6107 case ISD::INSERT_VECTOR_ELT: { 6108 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6109 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6110 // for scalable vectors where we will generate appropriate code to 6111 // deal with out-of-bounds cases correctly. 6112 if (N3C && N1.getValueType().isFixedLengthVector() && 6113 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6114 return getUNDEF(VT); 6115 6116 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6117 if (N3.isUndef()) 6118 return getUNDEF(VT); 6119 6120 // If the inserted element is an UNDEF, just use the input vector. 6121 if (N2.isUndef()) 6122 return N1; 6123 6124 break; 6125 } 6126 case ISD::INSERT_SUBVECTOR: { 6127 // Inserting undef into undef is still undef. 6128 if (N1.isUndef() && N2.isUndef()) 6129 return getUNDEF(VT); 6130 6131 EVT N2VT = N2.getValueType(); 6132 assert(VT == N1.getValueType() && 6133 "Dest and insert subvector source types must match!"); 6134 assert(VT.isVector() && N2VT.isVector() && 6135 "Insert subvector VTs must be vectors!"); 6136 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6137 "Cannot insert a scalable vector into a fixed length vector!"); 6138 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6139 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6140 "Insert subvector must be from smaller vector to larger vector!"); 6141 assert(isa<ConstantSDNode>(N3) && 6142 "Insert subvector index must be constant"); 6143 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6144 (N2VT.getVectorMinNumElements() + 6145 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6146 VT.getVectorMinNumElements()) && 6147 "Insert subvector overflow!"); 6148 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6149 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6150 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6151 6152 // Trivial insertion. 6153 if (VT == N2VT) 6154 return N2; 6155 6156 // If this is an insert of an extracted vector into an undef vector, we 6157 // can just use the input to the extract. 6158 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6159 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6160 return N2.getOperand(0); 6161 break; 6162 } 6163 case ISD::BITCAST: 6164 // Fold bit_convert nodes from a type to themselves. 6165 if (N1.getValueType() == VT) 6166 return N1; 6167 break; 6168 } 6169 6170 // Memoize node if it doesn't produce a flag. 6171 SDNode *N; 6172 SDVTList VTs = getVTList(VT); 6173 SDValue Ops[] = {N1, N2, N3}; 6174 if (VT != MVT::Glue) { 6175 FoldingSetNodeID ID; 6176 AddNodeIDNode(ID, Opcode, VTs, Ops); 6177 void *IP = nullptr; 6178 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6179 E->intersectFlagsWith(Flags); 6180 return SDValue(E, 0); 6181 } 6182 6183 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6184 N->setFlags(Flags); 6185 createOperands(N, Ops); 6186 CSEMap.InsertNode(N, IP); 6187 } else { 6188 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6189 createOperands(N, Ops); 6190 } 6191 6192 InsertNode(N); 6193 SDValue V = SDValue(N, 0); 6194 NewSDValueDbgMsg(V, "Creating new node: ", this); 6195 return V; 6196 } 6197 6198 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6199 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6200 SDValue Ops[] = { N1, N2, N3, N4 }; 6201 return getNode(Opcode, DL, VT, Ops); 6202 } 6203 6204 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6205 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6206 SDValue N5) { 6207 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6208 return getNode(Opcode, DL, VT, Ops); 6209 } 6210 6211 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6212 /// the incoming stack arguments to be loaded from the stack. 6213 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6214 SmallVector<SDValue, 8> ArgChains; 6215 6216 // Include the original chain at the beginning of the list. When this is 6217 // used by target LowerCall hooks, this helps legalize find the 6218 // CALLSEQ_BEGIN node. 6219 ArgChains.push_back(Chain); 6220 6221 // Add a chain value for each stack argument. 6222 for (SDNode *U : getEntryNode().getNode()->uses()) 6223 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6224 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6225 if (FI->getIndex() < 0) 6226 ArgChains.push_back(SDValue(L, 1)); 6227 6228 // Build a tokenfactor for all the chains. 6229 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6230 } 6231 6232 /// getMemsetValue - Vectorized representation of the memset value 6233 /// operand. 6234 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6235 const SDLoc &dl) { 6236 assert(!Value.isUndef()); 6237 6238 unsigned NumBits = VT.getScalarSizeInBits(); 6239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6240 assert(C->getAPIntValue().getBitWidth() == 8); 6241 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6242 if (VT.isInteger()) { 6243 bool IsOpaque = VT.getSizeInBits() > 64 || 6244 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6245 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6246 } 6247 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6248 VT); 6249 } 6250 6251 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6252 EVT IntVT = VT.getScalarType(); 6253 if (!IntVT.isInteger()) 6254 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6255 6256 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6257 if (NumBits > 8) { 6258 // Use a multiplication with 0x010101... to extend the input to the 6259 // required length. 6260 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6261 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6262 DAG.getConstant(Magic, dl, IntVT)); 6263 } 6264 6265 if (VT != Value.getValueType() && !VT.isInteger()) 6266 Value = DAG.getBitcast(VT.getScalarType(), Value); 6267 if (VT != Value.getValueType()) 6268 Value = DAG.getSplatBuildVector(VT, dl, Value); 6269 6270 return Value; 6271 } 6272 6273 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6274 /// used when a memcpy is turned into a memset when the source is a constant 6275 /// string ptr. 6276 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6277 const TargetLowering &TLI, 6278 const ConstantDataArraySlice &Slice) { 6279 // Handle vector with all elements zero. 6280 if (Slice.Array == nullptr) { 6281 if (VT.isInteger()) 6282 return DAG.getConstant(0, dl, VT); 6283 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6284 return DAG.getConstantFP(0.0, dl, VT); 6285 if (VT.isVector()) { 6286 unsigned NumElts = VT.getVectorNumElements(); 6287 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6288 return DAG.getNode(ISD::BITCAST, dl, VT, 6289 DAG.getConstant(0, dl, 6290 EVT::getVectorVT(*DAG.getContext(), 6291 EltVT, NumElts))); 6292 } 6293 llvm_unreachable("Expected type!"); 6294 } 6295 6296 assert(!VT.isVector() && "Can't handle vector type here!"); 6297 unsigned NumVTBits = VT.getSizeInBits(); 6298 unsigned NumVTBytes = NumVTBits / 8; 6299 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6300 6301 APInt Val(NumVTBits, 0); 6302 if (DAG.getDataLayout().isLittleEndian()) { 6303 for (unsigned i = 0; i != NumBytes; ++i) 6304 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6305 } else { 6306 for (unsigned i = 0; i != NumBytes; ++i) 6307 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6308 } 6309 6310 // If the "cost" of materializing the integer immediate is less than the cost 6311 // of a load, then it is cost effective to turn the load into the immediate. 6312 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6313 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6314 return DAG.getConstant(Val, dl, VT); 6315 return SDValue(nullptr, 0); 6316 } 6317 6318 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6319 const SDLoc &DL, 6320 const SDNodeFlags Flags) { 6321 EVT VT = Base.getValueType(); 6322 SDValue Index; 6323 6324 if (Offset.isScalable()) 6325 Index = getVScale(DL, Base.getValueType(), 6326 APInt(Base.getValueSizeInBits().getFixedSize(), 6327 Offset.getKnownMinSize())); 6328 else 6329 Index = getConstant(Offset.getFixedSize(), DL, VT); 6330 6331 return getMemBasePlusOffset(Base, Index, DL, Flags); 6332 } 6333 6334 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6335 const SDLoc &DL, 6336 const SDNodeFlags Flags) { 6337 assert(Offset.getValueType().isInteger()); 6338 EVT BasePtrVT = Ptr.getValueType(); 6339 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6340 } 6341 6342 /// Returns true if memcpy source is constant data. 6343 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6344 uint64_t SrcDelta = 0; 6345 GlobalAddressSDNode *G = nullptr; 6346 if (Src.getOpcode() == ISD::GlobalAddress) 6347 G = cast<GlobalAddressSDNode>(Src); 6348 else if (Src.getOpcode() == ISD::ADD && 6349 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6350 Src.getOperand(1).getOpcode() == ISD::Constant) { 6351 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6352 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6353 } 6354 if (!G) 6355 return false; 6356 6357 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6358 SrcDelta + G->getOffset()); 6359 } 6360 6361 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6362 SelectionDAG &DAG) { 6363 // On Darwin, -Os means optimize for size without hurting performance, so 6364 // only really optimize for size when -Oz (MinSize) is used. 6365 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6366 return MF.getFunction().hasMinSize(); 6367 return DAG.shouldOptForSize(); 6368 } 6369 6370 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6371 SmallVector<SDValue, 32> &OutChains, unsigned From, 6372 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6373 SmallVector<SDValue, 16> &OutStoreChains) { 6374 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6375 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6376 SmallVector<SDValue, 16> GluedLoadChains; 6377 for (unsigned i = From; i < To; ++i) { 6378 OutChains.push_back(OutLoadChains[i]); 6379 GluedLoadChains.push_back(OutLoadChains[i]); 6380 } 6381 6382 // Chain for all loads. 6383 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6384 GluedLoadChains); 6385 6386 for (unsigned i = From; i < To; ++i) { 6387 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6388 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6389 ST->getBasePtr(), ST->getMemoryVT(), 6390 ST->getMemOperand()); 6391 OutChains.push_back(NewStore); 6392 } 6393 } 6394 6395 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6396 SDValue Chain, SDValue Dst, SDValue Src, 6397 uint64_t Size, Align Alignment, 6398 bool isVol, bool AlwaysInline, 6399 MachinePointerInfo DstPtrInfo, 6400 MachinePointerInfo SrcPtrInfo, 6401 const AAMDNodes &AAInfo) { 6402 // Turn a memcpy of undef to nop. 6403 // FIXME: We need to honor volatile even is Src is undef. 6404 if (Src.isUndef()) 6405 return Chain; 6406 6407 // Expand memcpy to a series of load and store ops if the size operand falls 6408 // below a certain threshold. 6409 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6410 // rather than maybe a humongous number of loads and stores. 6411 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6412 const DataLayout &DL = DAG.getDataLayout(); 6413 LLVMContext &C = *DAG.getContext(); 6414 std::vector<EVT> MemOps; 6415 bool DstAlignCanChange = false; 6416 MachineFunction &MF = DAG.getMachineFunction(); 6417 MachineFrameInfo &MFI = MF.getFrameInfo(); 6418 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6419 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6420 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6421 DstAlignCanChange = true; 6422 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6423 if (!SrcAlign || Alignment > *SrcAlign) 6424 SrcAlign = Alignment; 6425 assert(SrcAlign && "SrcAlign must be set"); 6426 ConstantDataArraySlice Slice; 6427 // If marked as volatile, perform a copy even when marked as constant. 6428 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6429 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6430 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6431 const MemOp Op = isZeroConstant 6432 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6433 /*IsZeroMemset*/ true, isVol) 6434 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6435 *SrcAlign, isVol, CopyFromConstant); 6436 if (!TLI.findOptimalMemOpLowering( 6437 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6438 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6439 return SDValue(); 6440 6441 if (DstAlignCanChange) { 6442 Type *Ty = MemOps[0].getTypeForEVT(C); 6443 Align NewAlign = DL.getABITypeAlign(Ty); 6444 6445 // Don't promote to an alignment that would require dynamic stack 6446 // realignment. 6447 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6448 if (!TRI->hasStackRealignment(MF)) 6449 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6450 NewAlign = NewAlign / 2; 6451 6452 if (NewAlign > Alignment) { 6453 // Give the stack frame object a larger alignment if needed. 6454 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6455 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6456 Alignment = NewAlign; 6457 } 6458 } 6459 6460 // Prepare AAInfo for loads/stores after lowering this memcpy. 6461 AAMDNodes NewAAInfo = AAInfo; 6462 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6463 6464 MachineMemOperand::Flags MMOFlags = 6465 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6466 SmallVector<SDValue, 16> OutLoadChains; 6467 SmallVector<SDValue, 16> OutStoreChains; 6468 SmallVector<SDValue, 32> OutChains; 6469 unsigned NumMemOps = MemOps.size(); 6470 uint64_t SrcOff = 0, DstOff = 0; 6471 for (unsigned i = 0; i != NumMemOps; ++i) { 6472 EVT VT = MemOps[i]; 6473 unsigned VTSize = VT.getSizeInBits() / 8; 6474 SDValue Value, Store; 6475 6476 if (VTSize > Size) { 6477 // Issuing an unaligned load / store pair that overlaps with the previous 6478 // pair. Adjust the offset accordingly. 6479 assert(i == NumMemOps-1 && i != 0); 6480 SrcOff -= VTSize - Size; 6481 DstOff -= VTSize - Size; 6482 } 6483 6484 if (CopyFromConstant && 6485 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6486 // It's unlikely a store of a vector immediate can be done in a single 6487 // instruction. It would require a load from a constantpool first. 6488 // We only handle zero vectors here. 6489 // FIXME: Handle other cases where store of vector immediate is done in 6490 // a single instruction. 6491 ConstantDataArraySlice SubSlice; 6492 if (SrcOff < Slice.Length) { 6493 SubSlice = Slice; 6494 SubSlice.move(SrcOff); 6495 } else { 6496 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6497 SubSlice.Array = nullptr; 6498 SubSlice.Offset = 0; 6499 SubSlice.Length = VTSize; 6500 } 6501 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6502 if (Value.getNode()) { 6503 Store = DAG.getStore( 6504 Chain, dl, Value, 6505 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6506 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6507 OutChains.push_back(Store); 6508 } 6509 } 6510 6511 if (!Store.getNode()) { 6512 // The type might not be legal for the target. This should only happen 6513 // if the type is smaller than a legal type, as on PPC, so the right 6514 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6515 // to Load/Store if NVT==VT. 6516 // FIXME does the case above also need this? 6517 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6518 assert(NVT.bitsGE(VT)); 6519 6520 bool isDereferenceable = 6521 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6522 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6523 if (isDereferenceable) 6524 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6525 6526 Value = DAG.getExtLoad( 6527 ISD::EXTLOAD, dl, NVT, Chain, 6528 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6529 SrcPtrInfo.getWithOffset(SrcOff), VT, 6530 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6531 OutLoadChains.push_back(Value.getValue(1)); 6532 6533 Store = DAG.getTruncStore( 6534 Chain, dl, Value, 6535 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6536 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6537 OutStoreChains.push_back(Store); 6538 } 6539 SrcOff += VTSize; 6540 DstOff += VTSize; 6541 Size -= VTSize; 6542 } 6543 6544 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6545 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6546 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6547 6548 if (NumLdStInMemcpy) { 6549 // It may be that memcpy might be converted to memset if it's memcpy 6550 // of constants. In such a case, we won't have loads and stores, but 6551 // just stores. In the absence of loads, there is nothing to gang up. 6552 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6553 // If target does not care, just leave as it. 6554 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6555 OutChains.push_back(OutLoadChains[i]); 6556 OutChains.push_back(OutStoreChains[i]); 6557 } 6558 } else { 6559 // Ld/St less than/equal limit set by target. 6560 if (NumLdStInMemcpy <= GluedLdStLimit) { 6561 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6562 NumLdStInMemcpy, OutLoadChains, 6563 OutStoreChains); 6564 } else { 6565 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6566 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6567 unsigned GlueIter = 0; 6568 6569 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6570 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6571 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6572 6573 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6574 OutLoadChains, OutStoreChains); 6575 GlueIter += GluedLdStLimit; 6576 } 6577 6578 // Residual ld/st. 6579 if (RemainingLdStInMemcpy) { 6580 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6581 RemainingLdStInMemcpy, OutLoadChains, 6582 OutStoreChains); 6583 } 6584 } 6585 } 6586 } 6587 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6588 } 6589 6590 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6591 SDValue Chain, SDValue Dst, SDValue Src, 6592 uint64_t Size, Align Alignment, 6593 bool isVol, bool AlwaysInline, 6594 MachinePointerInfo DstPtrInfo, 6595 MachinePointerInfo SrcPtrInfo, 6596 const AAMDNodes &AAInfo) { 6597 // Turn a memmove of undef to nop. 6598 // FIXME: We need to honor volatile even is Src is undef. 6599 if (Src.isUndef()) 6600 return Chain; 6601 6602 // Expand memmove to a series of load and store ops if the size operand falls 6603 // below a certain threshold. 6604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6605 const DataLayout &DL = DAG.getDataLayout(); 6606 LLVMContext &C = *DAG.getContext(); 6607 std::vector<EVT> MemOps; 6608 bool DstAlignCanChange = false; 6609 MachineFunction &MF = DAG.getMachineFunction(); 6610 MachineFrameInfo &MFI = MF.getFrameInfo(); 6611 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6612 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6613 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6614 DstAlignCanChange = true; 6615 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6616 if (!SrcAlign || Alignment > *SrcAlign) 6617 SrcAlign = Alignment; 6618 assert(SrcAlign && "SrcAlign must be set"); 6619 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6620 if (!TLI.findOptimalMemOpLowering( 6621 MemOps, Limit, 6622 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6623 /*IsVolatile*/ true), 6624 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6625 MF.getFunction().getAttributes())) 6626 return SDValue(); 6627 6628 if (DstAlignCanChange) { 6629 Type *Ty = MemOps[0].getTypeForEVT(C); 6630 Align NewAlign = DL.getABITypeAlign(Ty); 6631 if (NewAlign > Alignment) { 6632 // Give the stack frame object a larger alignment if needed. 6633 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6634 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6635 Alignment = NewAlign; 6636 } 6637 } 6638 6639 // Prepare AAInfo for loads/stores after lowering this memmove. 6640 AAMDNodes NewAAInfo = AAInfo; 6641 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6642 6643 MachineMemOperand::Flags MMOFlags = 6644 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6645 uint64_t SrcOff = 0, DstOff = 0; 6646 SmallVector<SDValue, 8> LoadValues; 6647 SmallVector<SDValue, 8> LoadChains; 6648 SmallVector<SDValue, 8> OutChains; 6649 unsigned NumMemOps = MemOps.size(); 6650 for (unsigned i = 0; i < NumMemOps; i++) { 6651 EVT VT = MemOps[i]; 6652 unsigned VTSize = VT.getSizeInBits() / 8; 6653 SDValue Value; 6654 6655 bool isDereferenceable = 6656 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6657 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6658 if (isDereferenceable) 6659 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6660 6661 Value = DAG.getLoad( 6662 VT, dl, Chain, 6663 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6664 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6665 LoadValues.push_back(Value); 6666 LoadChains.push_back(Value.getValue(1)); 6667 SrcOff += VTSize; 6668 } 6669 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6670 OutChains.clear(); 6671 for (unsigned i = 0; i < NumMemOps; i++) { 6672 EVT VT = MemOps[i]; 6673 unsigned VTSize = VT.getSizeInBits() / 8; 6674 SDValue Store; 6675 6676 Store = DAG.getStore( 6677 Chain, dl, LoadValues[i], 6678 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6679 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6680 OutChains.push_back(Store); 6681 DstOff += VTSize; 6682 } 6683 6684 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6685 } 6686 6687 /// Lower the call to 'memset' intrinsic function into a series of store 6688 /// operations. 6689 /// 6690 /// \param DAG Selection DAG where lowered code is placed. 6691 /// \param dl Link to corresponding IR location. 6692 /// \param Chain Control flow dependency. 6693 /// \param Dst Pointer to destination memory location. 6694 /// \param Src Value of byte to write into the memory. 6695 /// \param Size Number of bytes to write. 6696 /// \param Alignment Alignment of the destination in bytes. 6697 /// \param isVol True if destination is volatile. 6698 /// \param DstPtrInfo IR information on the memory pointer. 6699 /// \returns New head in the control flow, if lowering was successful, empty 6700 /// SDValue otherwise. 6701 /// 6702 /// The function tries to replace 'llvm.memset' intrinsic with several store 6703 /// operations and value calculation code. This is usually profitable for small 6704 /// memory size. 6705 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6706 SDValue Chain, SDValue Dst, SDValue Src, 6707 uint64_t Size, Align Alignment, bool isVol, 6708 MachinePointerInfo DstPtrInfo, 6709 const AAMDNodes &AAInfo) { 6710 // Turn a memset of undef to nop. 6711 // FIXME: We need to honor volatile even is Src is undef. 6712 if (Src.isUndef()) 6713 return Chain; 6714 6715 // Expand memset to a series of load/store ops if the size operand 6716 // falls below a certain threshold. 6717 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6718 std::vector<EVT> MemOps; 6719 bool DstAlignCanChange = false; 6720 MachineFunction &MF = DAG.getMachineFunction(); 6721 MachineFrameInfo &MFI = MF.getFrameInfo(); 6722 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6723 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6724 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6725 DstAlignCanChange = true; 6726 bool IsZeroVal = 6727 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6728 if (!TLI.findOptimalMemOpLowering( 6729 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6730 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6731 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6732 return SDValue(); 6733 6734 if (DstAlignCanChange) { 6735 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6736 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6737 if (NewAlign > Alignment) { 6738 // Give the stack frame object a larger alignment if needed. 6739 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6740 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6741 Alignment = NewAlign; 6742 } 6743 } 6744 6745 SmallVector<SDValue, 8> OutChains; 6746 uint64_t DstOff = 0; 6747 unsigned NumMemOps = MemOps.size(); 6748 6749 // Find the largest store and generate the bit pattern for it. 6750 EVT LargestVT = MemOps[0]; 6751 for (unsigned i = 1; i < NumMemOps; i++) 6752 if (MemOps[i].bitsGT(LargestVT)) 6753 LargestVT = MemOps[i]; 6754 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6755 6756 // Prepare AAInfo for loads/stores after lowering this memset. 6757 AAMDNodes NewAAInfo = AAInfo; 6758 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6759 6760 for (unsigned i = 0; i < NumMemOps; i++) { 6761 EVT VT = MemOps[i]; 6762 unsigned VTSize = VT.getSizeInBits() / 8; 6763 if (VTSize > Size) { 6764 // Issuing an unaligned load / store pair that overlaps with the previous 6765 // pair. Adjust the offset accordingly. 6766 assert(i == NumMemOps-1 && i != 0); 6767 DstOff -= VTSize - Size; 6768 } 6769 6770 // If this store is smaller than the largest store see whether we can get 6771 // the smaller value for free with a truncate. 6772 SDValue Value = MemSetValue; 6773 if (VT.bitsLT(LargestVT)) { 6774 if (!LargestVT.isVector() && !VT.isVector() && 6775 TLI.isTruncateFree(LargestVT, VT)) 6776 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6777 else 6778 Value = getMemsetValue(Src, VT, DAG, dl); 6779 } 6780 assert(Value.getValueType() == VT && "Value with wrong type."); 6781 SDValue Store = DAG.getStore( 6782 Chain, dl, Value, 6783 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6784 DstPtrInfo.getWithOffset(DstOff), Alignment, 6785 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6786 NewAAInfo); 6787 OutChains.push_back(Store); 6788 DstOff += VT.getSizeInBits() / 8; 6789 Size -= VTSize; 6790 } 6791 6792 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6793 } 6794 6795 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6796 unsigned AS) { 6797 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6798 // pointer operands can be losslessly bitcasted to pointers of address space 0 6799 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6800 report_fatal_error("cannot lower memory intrinsic in address space " + 6801 Twine(AS)); 6802 } 6803 } 6804 6805 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6806 SDValue Src, SDValue Size, Align Alignment, 6807 bool isVol, bool AlwaysInline, bool isTailCall, 6808 MachinePointerInfo DstPtrInfo, 6809 MachinePointerInfo SrcPtrInfo, 6810 const AAMDNodes &AAInfo) { 6811 // Check to see if we should lower the memcpy to loads and stores first. 6812 // For cases within the target-specified limits, this is the best choice. 6813 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6814 if (ConstantSize) { 6815 // Memcpy with size zero? Just return the original chain. 6816 if (ConstantSize->isZero()) 6817 return Chain; 6818 6819 SDValue Result = getMemcpyLoadsAndStores( 6820 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6821 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6822 if (Result.getNode()) 6823 return Result; 6824 } 6825 6826 // Then check to see if we should lower the memcpy with target-specific 6827 // code. If the target chooses to do this, this is the next best. 6828 if (TSI) { 6829 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6830 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6831 DstPtrInfo, SrcPtrInfo); 6832 if (Result.getNode()) 6833 return Result; 6834 } 6835 6836 // If we really need inline code and the target declined to provide it, 6837 // use a (potentially long) sequence of loads and stores. 6838 if (AlwaysInline) { 6839 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6840 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6841 ConstantSize->getZExtValue(), Alignment, 6842 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6843 } 6844 6845 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6846 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6847 6848 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6849 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6850 // respect volatile, so they may do things like read or write memory 6851 // beyond the given memory regions. But fixing this isn't easy, and most 6852 // people don't care. 6853 6854 // Emit a library call. 6855 TargetLowering::ArgListTy Args; 6856 TargetLowering::ArgListEntry Entry; 6857 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6858 Entry.Node = Dst; Args.push_back(Entry); 6859 Entry.Node = Src; Args.push_back(Entry); 6860 6861 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6862 Entry.Node = Size; Args.push_back(Entry); 6863 // FIXME: pass in SDLoc 6864 TargetLowering::CallLoweringInfo CLI(*this); 6865 CLI.setDebugLoc(dl) 6866 .setChain(Chain) 6867 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6868 Dst.getValueType().getTypeForEVT(*getContext()), 6869 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6870 TLI->getPointerTy(getDataLayout())), 6871 std::move(Args)) 6872 .setDiscardResult() 6873 .setTailCall(isTailCall); 6874 6875 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6876 return CallResult.second; 6877 } 6878 6879 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6880 SDValue Dst, unsigned DstAlign, 6881 SDValue Src, unsigned SrcAlign, 6882 SDValue Size, Type *SizeTy, 6883 unsigned ElemSz, bool isTailCall, 6884 MachinePointerInfo DstPtrInfo, 6885 MachinePointerInfo SrcPtrInfo) { 6886 // Emit a library call. 6887 TargetLowering::ArgListTy Args; 6888 TargetLowering::ArgListEntry Entry; 6889 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6890 Entry.Node = Dst; 6891 Args.push_back(Entry); 6892 6893 Entry.Node = Src; 6894 Args.push_back(Entry); 6895 6896 Entry.Ty = SizeTy; 6897 Entry.Node = Size; 6898 Args.push_back(Entry); 6899 6900 RTLIB::Libcall LibraryCall = 6901 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6902 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6903 report_fatal_error("Unsupported element size"); 6904 6905 TargetLowering::CallLoweringInfo CLI(*this); 6906 CLI.setDebugLoc(dl) 6907 .setChain(Chain) 6908 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6909 Type::getVoidTy(*getContext()), 6910 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6911 TLI->getPointerTy(getDataLayout())), 6912 std::move(Args)) 6913 .setDiscardResult() 6914 .setTailCall(isTailCall); 6915 6916 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6917 return CallResult.second; 6918 } 6919 6920 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6921 SDValue Src, SDValue Size, Align Alignment, 6922 bool isVol, bool isTailCall, 6923 MachinePointerInfo DstPtrInfo, 6924 MachinePointerInfo SrcPtrInfo, 6925 const AAMDNodes &AAInfo) { 6926 // Check to see if we should lower the memmove to loads and stores first. 6927 // For cases within the target-specified limits, this is the best choice. 6928 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6929 if (ConstantSize) { 6930 // Memmove with size zero? Just return the original chain. 6931 if (ConstantSize->isZero()) 6932 return Chain; 6933 6934 SDValue Result = getMemmoveLoadsAndStores( 6935 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6936 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6937 if (Result.getNode()) 6938 return Result; 6939 } 6940 6941 // Then check to see if we should lower the memmove with target-specific 6942 // code. If the target chooses to do this, this is the next best. 6943 if (TSI) { 6944 SDValue Result = 6945 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6946 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6947 if (Result.getNode()) 6948 return Result; 6949 } 6950 6951 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6952 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6953 6954 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6955 // not be safe. See memcpy above for more details. 6956 6957 // Emit a library call. 6958 TargetLowering::ArgListTy Args; 6959 TargetLowering::ArgListEntry Entry; 6960 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6961 Entry.Node = Dst; Args.push_back(Entry); 6962 Entry.Node = Src; Args.push_back(Entry); 6963 6964 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6965 Entry.Node = Size; Args.push_back(Entry); 6966 // FIXME: pass in SDLoc 6967 TargetLowering::CallLoweringInfo CLI(*this); 6968 CLI.setDebugLoc(dl) 6969 .setChain(Chain) 6970 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6971 Dst.getValueType().getTypeForEVT(*getContext()), 6972 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6973 TLI->getPointerTy(getDataLayout())), 6974 std::move(Args)) 6975 .setDiscardResult() 6976 .setTailCall(isTailCall); 6977 6978 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6979 return CallResult.second; 6980 } 6981 6982 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6983 SDValue Dst, unsigned DstAlign, 6984 SDValue Src, unsigned SrcAlign, 6985 SDValue Size, Type *SizeTy, 6986 unsigned ElemSz, bool isTailCall, 6987 MachinePointerInfo DstPtrInfo, 6988 MachinePointerInfo SrcPtrInfo) { 6989 // Emit a library call. 6990 TargetLowering::ArgListTy Args; 6991 TargetLowering::ArgListEntry Entry; 6992 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6993 Entry.Node = Dst; 6994 Args.push_back(Entry); 6995 6996 Entry.Node = Src; 6997 Args.push_back(Entry); 6998 6999 Entry.Ty = SizeTy; 7000 Entry.Node = Size; 7001 Args.push_back(Entry); 7002 7003 RTLIB::Libcall LibraryCall = 7004 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7005 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7006 report_fatal_error("Unsupported element size"); 7007 7008 TargetLowering::CallLoweringInfo CLI(*this); 7009 CLI.setDebugLoc(dl) 7010 .setChain(Chain) 7011 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7012 Type::getVoidTy(*getContext()), 7013 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7014 TLI->getPointerTy(getDataLayout())), 7015 std::move(Args)) 7016 .setDiscardResult() 7017 .setTailCall(isTailCall); 7018 7019 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7020 return CallResult.second; 7021 } 7022 7023 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7024 SDValue Src, SDValue Size, Align Alignment, 7025 bool isVol, bool isTailCall, 7026 MachinePointerInfo DstPtrInfo, 7027 const AAMDNodes &AAInfo) { 7028 // Check to see if we should lower the memset to stores first. 7029 // For cases within the target-specified limits, this is the best choice. 7030 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7031 if (ConstantSize) { 7032 // Memset with size zero? Just return the original chain. 7033 if (ConstantSize->isZero()) 7034 return Chain; 7035 7036 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7037 ConstantSize->getZExtValue(), Alignment, 7038 isVol, DstPtrInfo, AAInfo); 7039 7040 if (Result.getNode()) 7041 return Result; 7042 } 7043 7044 // Then check to see if we should lower the memset with target-specific 7045 // code. If the target chooses to do this, this is the next best. 7046 if (TSI) { 7047 SDValue Result = TSI->EmitTargetCodeForMemset( 7048 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7049 if (Result.getNode()) 7050 return Result; 7051 } 7052 7053 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7054 7055 // Emit a library call. 7056 TargetLowering::ArgListTy Args; 7057 TargetLowering::ArgListEntry Entry; 7058 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7059 Args.push_back(Entry); 7060 Entry.Node = Src; 7061 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7062 Args.push_back(Entry); 7063 Entry.Node = Size; 7064 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7065 Args.push_back(Entry); 7066 7067 // FIXME: pass in SDLoc 7068 TargetLowering::CallLoweringInfo CLI(*this); 7069 CLI.setDebugLoc(dl) 7070 .setChain(Chain) 7071 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7072 Dst.getValueType().getTypeForEVT(*getContext()), 7073 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7074 TLI->getPointerTy(getDataLayout())), 7075 std::move(Args)) 7076 .setDiscardResult() 7077 .setTailCall(isTailCall); 7078 7079 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7080 return CallResult.second; 7081 } 7082 7083 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7084 SDValue Dst, unsigned DstAlign, 7085 SDValue Value, SDValue Size, Type *SizeTy, 7086 unsigned ElemSz, bool isTailCall, 7087 MachinePointerInfo DstPtrInfo) { 7088 // Emit a library call. 7089 TargetLowering::ArgListTy Args; 7090 TargetLowering::ArgListEntry Entry; 7091 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7092 Entry.Node = Dst; 7093 Args.push_back(Entry); 7094 7095 Entry.Ty = Type::getInt8Ty(*getContext()); 7096 Entry.Node = Value; 7097 Args.push_back(Entry); 7098 7099 Entry.Ty = SizeTy; 7100 Entry.Node = Size; 7101 Args.push_back(Entry); 7102 7103 RTLIB::Libcall LibraryCall = 7104 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7105 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7106 report_fatal_error("Unsupported element size"); 7107 7108 TargetLowering::CallLoweringInfo CLI(*this); 7109 CLI.setDebugLoc(dl) 7110 .setChain(Chain) 7111 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7112 Type::getVoidTy(*getContext()), 7113 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7114 TLI->getPointerTy(getDataLayout())), 7115 std::move(Args)) 7116 .setDiscardResult() 7117 .setTailCall(isTailCall); 7118 7119 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7120 return CallResult.second; 7121 } 7122 7123 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7124 SDVTList VTList, ArrayRef<SDValue> Ops, 7125 MachineMemOperand *MMO) { 7126 FoldingSetNodeID ID; 7127 ID.AddInteger(MemVT.getRawBits()); 7128 AddNodeIDNode(ID, Opcode, VTList, Ops); 7129 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7130 void* IP = nullptr; 7131 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7132 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7133 return SDValue(E, 0); 7134 } 7135 7136 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7137 VTList, MemVT, MMO); 7138 createOperands(N, Ops); 7139 7140 CSEMap.InsertNode(N, IP); 7141 InsertNode(N); 7142 return SDValue(N, 0); 7143 } 7144 7145 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7146 EVT MemVT, SDVTList VTs, SDValue Chain, 7147 SDValue Ptr, SDValue Cmp, SDValue Swp, 7148 MachineMemOperand *MMO) { 7149 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7150 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7151 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7152 7153 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7154 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7155 } 7156 7157 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7158 SDValue Chain, SDValue Ptr, SDValue Val, 7159 MachineMemOperand *MMO) { 7160 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7161 Opcode == ISD::ATOMIC_LOAD_SUB || 7162 Opcode == ISD::ATOMIC_LOAD_AND || 7163 Opcode == ISD::ATOMIC_LOAD_CLR || 7164 Opcode == ISD::ATOMIC_LOAD_OR || 7165 Opcode == ISD::ATOMIC_LOAD_XOR || 7166 Opcode == ISD::ATOMIC_LOAD_NAND || 7167 Opcode == ISD::ATOMIC_LOAD_MIN || 7168 Opcode == ISD::ATOMIC_LOAD_MAX || 7169 Opcode == ISD::ATOMIC_LOAD_UMIN || 7170 Opcode == ISD::ATOMIC_LOAD_UMAX || 7171 Opcode == ISD::ATOMIC_LOAD_FADD || 7172 Opcode == ISD::ATOMIC_LOAD_FSUB || 7173 Opcode == ISD::ATOMIC_SWAP || 7174 Opcode == ISD::ATOMIC_STORE) && 7175 "Invalid Atomic Op"); 7176 7177 EVT VT = Val.getValueType(); 7178 7179 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7180 getVTList(VT, MVT::Other); 7181 SDValue Ops[] = {Chain, Ptr, Val}; 7182 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7183 } 7184 7185 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7186 EVT VT, SDValue Chain, SDValue Ptr, 7187 MachineMemOperand *MMO) { 7188 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7189 7190 SDVTList VTs = getVTList(VT, MVT::Other); 7191 SDValue Ops[] = {Chain, Ptr}; 7192 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7193 } 7194 7195 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7196 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7197 if (Ops.size() == 1) 7198 return Ops[0]; 7199 7200 SmallVector<EVT, 4> VTs; 7201 VTs.reserve(Ops.size()); 7202 for (const SDValue &Op : Ops) 7203 VTs.push_back(Op.getValueType()); 7204 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7205 } 7206 7207 SDValue SelectionDAG::getMemIntrinsicNode( 7208 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7209 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7210 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7211 if (!Size && MemVT.isScalableVector()) 7212 Size = MemoryLocation::UnknownSize; 7213 else if (!Size) 7214 Size = MemVT.getStoreSize(); 7215 7216 MachineFunction &MF = getMachineFunction(); 7217 MachineMemOperand *MMO = 7218 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7219 7220 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7221 } 7222 7223 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7224 SDVTList VTList, 7225 ArrayRef<SDValue> Ops, EVT MemVT, 7226 MachineMemOperand *MMO) { 7227 assert((Opcode == ISD::INTRINSIC_VOID || 7228 Opcode == ISD::INTRINSIC_W_CHAIN || 7229 Opcode == ISD::PREFETCH || 7230 ((int)Opcode <= std::numeric_limits<int>::max() && 7231 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7232 "Opcode is not a memory-accessing opcode!"); 7233 7234 // Memoize the node unless it returns a flag. 7235 MemIntrinsicSDNode *N; 7236 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7237 FoldingSetNodeID ID; 7238 AddNodeIDNode(ID, Opcode, VTList, Ops); 7239 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7240 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7241 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7242 void *IP = nullptr; 7243 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7244 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7245 return SDValue(E, 0); 7246 } 7247 7248 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7249 VTList, MemVT, MMO); 7250 createOperands(N, Ops); 7251 7252 CSEMap.InsertNode(N, IP); 7253 } else { 7254 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7255 VTList, MemVT, MMO); 7256 createOperands(N, Ops); 7257 } 7258 InsertNode(N); 7259 SDValue V(N, 0); 7260 NewSDValueDbgMsg(V, "Creating new node: ", this); 7261 return V; 7262 } 7263 7264 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7265 SDValue Chain, int FrameIndex, 7266 int64_t Size, int64_t Offset) { 7267 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7268 const auto VTs = getVTList(MVT::Other); 7269 SDValue Ops[2] = { 7270 Chain, 7271 getFrameIndex(FrameIndex, 7272 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7273 true)}; 7274 7275 FoldingSetNodeID ID; 7276 AddNodeIDNode(ID, Opcode, VTs, Ops); 7277 ID.AddInteger(FrameIndex); 7278 ID.AddInteger(Size); 7279 ID.AddInteger(Offset); 7280 void *IP = nullptr; 7281 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7282 return SDValue(E, 0); 7283 7284 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7285 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7286 createOperands(N, Ops); 7287 CSEMap.InsertNode(N, IP); 7288 InsertNode(N); 7289 SDValue V(N, 0); 7290 NewSDValueDbgMsg(V, "Creating new node: ", this); 7291 return V; 7292 } 7293 7294 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7295 uint64_t Guid, uint64_t Index, 7296 uint32_t Attr) { 7297 const unsigned Opcode = ISD::PSEUDO_PROBE; 7298 const auto VTs = getVTList(MVT::Other); 7299 SDValue Ops[] = {Chain}; 7300 FoldingSetNodeID ID; 7301 AddNodeIDNode(ID, Opcode, VTs, Ops); 7302 ID.AddInteger(Guid); 7303 ID.AddInteger(Index); 7304 void *IP = nullptr; 7305 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7306 return SDValue(E, 0); 7307 7308 auto *N = newSDNode<PseudoProbeSDNode>( 7309 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7310 createOperands(N, Ops); 7311 CSEMap.InsertNode(N, IP); 7312 InsertNode(N); 7313 SDValue V(N, 0); 7314 NewSDValueDbgMsg(V, "Creating new node: ", this); 7315 return V; 7316 } 7317 7318 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7319 /// MachinePointerInfo record from it. This is particularly useful because the 7320 /// code generator has many cases where it doesn't bother passing in a 7321 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7322 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7323 SelectionDAG &DAG, SDValue Ptr, 7324 int64_t Offset = 0) { 7325 // If this is FI+Offset, we can model it. 7326 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7327 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7328 FI->getIndex(), Offset); 7329 7330 // If this is (FI+Offset1)+Offset2, we can model it. 7331 if (Ptr.getOpcode() != ISD::ADD || 7332 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7333 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7334 return Info; 7335 7336 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7337 return MachinePointerInfo::getFixedStack( 7338 DAG.getMachineFunction(), FI, 7339 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7340 } 7341 7342 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7343 /// MachinePointerInfo record from it. This is particularly useful because the 7344 /// code generator has many cases where it doesn't bother passing in a 7345 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7346 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7347 SelectionDAG &DAG, SDValue Ptr, 7348 SDValue OffsetOp) { 7349 // If the 'Offset' value isn't a constant, we can't handle this. 7350 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7351 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7352 if (OffsetOp.isUndef()) 7353 return InferPointerInfo(Info, DAG, Ptr); 7354 return Info; 7355 } 7356 7357 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7358 EVT VT, const SDLoc &dl, SDValue Chain, 7359 SDValue Ptr, SDValue Offset, 7360 MachinePointerInfo PtrInfo, EVT MemVT, 7361 Align Alignment, 7362 MachineMemOperand::Flags MMOFlags, 7363 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7364 assert(Chain.getValueType() == MVT::Other && 7365 "Invalid chain type"); 7366 7367 MMOFlags |= MachineMemOperand::MOLoad; 7368 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7369 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7370 // clients. 7371 if (PtrInfo.V.isNull()) 7372 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7373 7374 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7375 MachineFunction &MF = getMachineFunction(); 7376 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7377 Alignment, AAInfo, Ranges); 7378 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7379 } 7380 7381 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7382 EVT VT, const SDLoc &dl, SDValue Chain, 7383 SDValue Ptr, SDValue Offset, EVT MemVT, 7384 MachineMemOperand *MMO) { 7385 if (VT == MemVT) { 7386 ExtType = ISD::NON_EXTLOAD; 7387 } else if (ExtType == ISD::NON_EXTLOAD) { 7388 assert(VT == MemVT && "Non-extending load from different memory type!"); 7389 } else { 7390 // Extending load. 7391 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7392 "Should only be an extending load, not truncating!"); 7393 assert(VT.isInteger() == MemVT.isInteger() && 7394 "Cannot convert from FP to Int or Int -> FP!"); 7395 assert(VT.isVector() == MemVT.isVector() && 7396 "Cannot use an ext load to convert to or from a vector!"); 7397 assert((!VT.isVector() || 7398 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7399 "Cannot use an ext load to change the number of vector elements!"); 7400 } 7401 7402 bool Indexed = AM != ISD::UNINDEXED; 7403 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7404 7405 SDVTList VTs = Indexed ? 7406 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7407 SDValue Ops[] = { Chain, Ptr, Offset }; 7408 FoldingSetNodeID ID; 7409 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7410 ID.AddInteger(MemVT.getRawBits()); 7411 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7412 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7413 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7414 void *IP = nullptr; 7415 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7416 cast<LoadSDNode>(E)->refineAlignment(MMO); 7417 return SDValue(E, 0); 7418 } 7419 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7420 ExtType, MemVT, MMO); 7421 createOperands(N, Ops); 7422 7423 CSEMap.InsertNode(N, IP); 7424 InsertNode(N); 7425 SDValue V(N, 0); 7426 NewSDValueDbgMsg(V, "Creating new node: ", this); 7427 return V; 7428 } 7429 7430 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7431 SDValue Ptr, MachinePointerInfo PtrInfo, 7432 MaybeAlign Alignment, 7433 MachineMemOperand::Flags MMOFlags, 7434 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7435 SDValue Undef = getUNDEF(Ptr.getValueType()); 7436 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7437 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7438 } 7439 7440 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7441 SDValue Ptr, MachineMemOperand *MMO) { 7442 SDValue Undef = getUNDEF(Ptr.getValueType()); 7443 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7444 VT, MMO); 7445 } 7446 7447 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7448 EVT VT, SDValue Chain, SDValue Ptr, 7449 MachinePointerInfo PtrInfo, EVT MemVT, 7450 MaybeAlign Alignment, 7451 MachineMemOperand::Flags MMOFlags, 7452 const AAMDNodes &AAInfo) { 7453 SDValue Undef = getUNDEF(Ptr.getValueType()); 7454 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7455 MemVT, Alignment, MMOFlags, AAInfo); 7456 } 7457 7458 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7459 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7460 MachineMemOperand *MMO) { 7461 SDValue Undef = getUNDEF(Ptr.getValueType()); 7462 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7463 MemVT, MMO); 7464 } 7465 7466 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7467 SDValue Base, SDValue Offset, 7468 ISD::MemIndexedMode AM) { 7469 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7470 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7471 // Don't propagate the invariant or dereferenceable flags. 7472 auto MMOFlags = 7473 LD->getMemOperand()->getFlags() & 7474 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7475 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7476 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7477 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7478 } 7479 7480 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7481 SDValue Ptr, MachinePointerInfo PtrInfo, 7482 Align Alignment, 7483 MachineMemOperand::Flags MMOFlags, 7484 const AAMDNodes &AAInfo) { 7485 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7486 7487 MMOFlags |= MachineMemOperand::MOStore; 7488 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7489 7490 if (PtrInfo.V.isNull()) 7491 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7492 7493 MachineFunction &MF = getMachineFunction(); 7494 uint64_t Size = 7495 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7496 MachineMemOperand *MMO = 7497 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7498 return getStore(Chain, dl, Val, Ptr, MMO); 7499 } 7500 7501 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7502 SDValue Ptr, MachineMemOperand *MMO) { 7503 assert(Chain.getValueType() == MVT::Other && 7504 "Invalid chain type"); 7505 EVT VT = Val.getValueType(); 7506 SDVTList VTs = getVTList(MVT::Other); 7507 SDValue Undef = getUNDEF(Ptr.getValueType()); 7508 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7509 FoldingSetNodeID ID; 7510 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7511 ID.AddInteger(VT.getRawBits()); 7512 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7513 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7514 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7515 void *IP = nullptr; 7516 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7517 cast<StoreSDNode>(E)->refineAlignment(MMO); 7518 return SDValue(E, 0); 7519 } 7520 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7521 ISD::UNINDEXED, false, VT, MMO); 7522 createOperands(N, Ops); 7523 7524 CSEMap.InsertNode(N, IP); 7525 InsertNode(N); 7526 SDValue V(N, 0); 7527 NewSDValueDbgMsg(V, "Creating new node: ", this); 7528 return V; 7529 } 7530 7531 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7532 SDValue Ptr, MachinePointerInfo PtrInfo, 7533 EVT SVT, Align Alignment, 7534 MachineMemOperand::Flags MMOFlags, 7535 const AAMDNodes &AAInfo) { 7536 assert(Chain.getValueType() == MVT::Other && 7537 "Invalid chain type"); 7538 7539 MMOFlags |= MachineMemOperand::MOStore; 7540 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7541 7542 if (PtrInfo.V.isNull()) 7543 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7544 7545 MachineFunction &MF = getMachineFunction(); 7546 MachineMemOperand *MMO = MF.getMachineMemOperand( 7547 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7548 Alignment, AAInfo); 7549 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7550 } 7551 7552 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7553 SDValue Ptr, EVT SVT, 7554 MachineMemOperand *MMO) { 7555 EVT VT = Val.getValueType(); 7556 7557 assert(Chain.getValueType() == MVT::Other && 7558 "Invalid chain type"); 7559 if (VT == SVT) 7560 return getStore(Chain, dl, Val, Ptr, MMO); 7561 7562 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7563 "Should only be a truncating store, not extending!"); 7564 assert(VT.isInteger() == SVT.isInteger() && 7565 "Can't do FP-INT conversion!"); 7566 assert(VT.isVector() == SVT.isVector() && 7567 "Cannot use trunc store to convert to or from a vector!"); 7568 assert((!VT.isVector() || 7569 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7570 "Cannot use trunc store to change the number of vector elements!"); 7571 7572 SDVTList VTs = getVTList(MVT::Other); 7573 SDValue Undef = getUNDEF(Ptr.getValueType()); 7574 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7575 FoldingSetNodeID ID; 7576 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7577 ID.AddInteger(SVT.getRawBits()); 7578 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7579 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7580 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7581 void *IP = nullptr; 7582 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7583 cast<StoreSDNode>(E)->refineAlignment(MMO); 7584 return SDValue(E, 0); 7585 } 7586 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7587 ISD::UNINDEXED, true, SVT, MMO); 7588 createOperands(N, Ops); 7589 7590 CSEMap.InsertNode(N, IP); 7591 InsertNode(N); 7592 SDValue V(N, 0); 7593 NewSDValueDbgMsg(V, "Creating new node: ", this); 7594 return V; 7595 } 7596 7597 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7598 SDValue Base, SDValue Offset, 7599 ISD::MemIndexedMode AM) { 7600 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7601 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7602 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7603 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7604 FoldingSetNodeID ID; 7605 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7606 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7607 ID.AddInteger(ST->getRawSubclassData()); 7608 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7609 void *IP = nullptr; 7610 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7611 return SDValue(E, 0); 7612 7613 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7614 ST->isTruncatingStore(), ST->getMemoryVT(), 7615 ST->getMemOperand()); 7616 createOperands(N, Ops); 7617 7618 CSEMap.InsertNode(N, IP); 7619 InsertNode(N); 7620 SDValue V(N, 0); 7621 NewSDValueDbgMsg(V, "Creating new node: ", this); 7622 return V; 7623 } 7624 7625 SDValue SelectionDAG::getLoadVP( 7626 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7627 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7628 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7629 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7630 const MDNode *Ranges, bool IsExpanding) { 7631 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7632 7633 MMOFlags |= MachineMemOperand::MOLoad; 7634 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7635 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7636 // clients. 7637 if (PtrInfo.V.isNull()) 7638 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7639 7640 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7641 MachineFunction &MF = getMachineFunction(); 7642 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7643 Alignment, AAInfo, Ranges); 7644 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7645 MMO, IsExpanding); 7646 } 7647 7648 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7649 ISD::LoadExtType ExtType, EVT VT, 7650 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7651 SDValue Offset, SDValue Mask, SDValue EVL, 7652 EVT MemVT, MachineMemOperand *MMO, 7653 bool IsExpanding) { 7654 if (VT == MemVT) { 7655 ExtType = ISD::NON_EXTLOAD; 7656 } else if (ExtType == ISD::NON_EXTLOAD) { 7657 assert(VT == MemVT && "Non-extending load from different memory type!"); 7658 } else { 7659 // Extending load. 7660 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7661 "Should only be an extending load, not truncating!"); 7662 assert(VT.isInteger() == MemVT.isInteger() && 7663 "Cannot convert from FP to Int or Int -> FP!"); 7664 assert(VT.isVector() == MemVT.isVector() && 7665 "Cannot use an ext load to convert to or from a vector!"); 7666 assert((!VT.isVector() || 7667 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7668 "Cannot use an ext load to change the number of vector elements!"); 7669 } 7670 7671 bool Indexed = AM != ISD::UNINDEXED; 7672 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7673 7674 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7675 : getVTList(VT, MVT::Other); 7676 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7677 FoldingSetNodeID ID; 7678 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7679 ID.AddInteger(VT.getRawBits()); 7680 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7681 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7682 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7683 void *IP = nullptr; 7684 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7685 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7686 return SDValue(E, 0); 7687 } 7688 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7689 ExtType, IsExpanding, MemVT, MMO); 7690 createOperands(N, Ops); 7691 7692 CSEMap.InsertNode(N, IP); 7693 InsertNode(N); 7694 SDValue V(N, 0); 7695 NewSDValueDbgMsg(V, "Creating new node: ", this); 7696 return V; 7697 } 7698 7699 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7700 SDValue Ptr, SDValue Mask, SDValue EVL, 7701 MachinePointerInfo PtrInfo, 7702 MaybeAlign Alignment, 7703 MachineMemOperand::Flags MMOFlags, 7704 const AAMDNodes &AAInfo, const MDNode *Ranges, 7705 bool IsExpanding) { 7706 SDValue Undef = getUNDEF(Ptr.getValueType()); 7707 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7708 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7709 IsExpanding); 7710 } 7711 7712 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7713 SDValue Ptr, SDValue Mask, SDValue EVL, 7714 MachineMemOperand *MMO, bool IsExpanding) { 7715 SDValue Undef = getUNDEF(Ptr.getValueType()); 7716 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7717 Mask, EVL, VT, MMO, IsExpanding); 7718 } 7719 7720 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7721 EVT VT, SDValue Chain, SDValue Ptr, 7722 SDValue Mask, SDValue EVL, 7723 MachinePointerInfo PtrInfo, EVT MemVT, 7724 MaybeAlign Alignment, 7725 MachineMemOperand::Flags MMOFlags, 7726 const AAMDNodes &AAInfo, bool IsExpanding) { 7727 SDValue Undef = getUNDEF(Ptr.getValueType()); 7728 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7729 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7730 IsExpanding); 7731 } 7732 7733 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7734 EVT VT, SDValue Chain, SDValue Ptr, 7735 SDValue Mask, SDValue EVL, EVT MemVT, 7736 MachineMemOperand *MMO, bool IsExpanding) { 7737 SDValue Undef = getUNDEF(Ptr.getValueType()); 7738 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7739 EVL, MemVT, MMO, IsExpanding); 7740 } 7741 7742 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7743 SDValue Base, SDValue Offset, 7744 ISD::MemIndexedMode AM) { 7745 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7746 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7747 // Don't propagate the invariant or dereferenceable flags. 7748 auto MMOFlags = 7749 LD->getMemOperand()->getFlags() & 7750 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7751 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7752 LD->getChain(), Base, Offset, LD->getMask(), 7753 LD->getVectorLength(), LD->getPointerInfo(), 7754 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7755 nullptr, LD->isExpandingLoad()); 7756 } 7757 7758 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7759 SDValue Ptr, SDValue Mask, SDValue EVL, 7760 MachinePointerInfo PtrInfo, Align Alignment, 7761 MachineMemOperand::Flags MMOFlags, 7762 const AAMDNodes &AAInfo, bool IsCompressing) { 7763 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7764 7765 MMOFlags |= MachineMemOperand::MOStore; 7766 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7767 7768 if (PtrInfo.V.isNull()) 7769 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7770 7771 MachineFunction &MF = getMachineFunction(); 7772 uint64_t Size = 7773 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7774 MachineMemOperand *MMO = 7775 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7776 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7777 } 7778 7779 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7780 SDValue Ptr, SDValue Mask, SDValue EVL, 7781 MachineMemOperand *MMO, bool IsCompressing) { 7782 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7783 EVT VT = Val.getValueType(); 7784 SDVTList VTs = getVTList(MVT::Other); 7785 SDValue Undef = getUNDEF(Ptr.getValueType()); 7786 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7787 FoldingSetNodeID ID; 7788 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7789 ID.AddInteger(VT.getRawBits()); 7790 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7791 dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO)); 7792 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7793 void *IP = nullptr; 7794 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7795 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7796 return SDValue(E, 0); 7797 } 7798 auto *N = 7799 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7800 ISD::UNINDEXED, false, IsCompressing, VT, MMO); 7801 createOperands(N, Ops); 7802 7803 CSEMap.InsertNode(N, IP); 7804 InsertNode(N); 7805 SDValue V(N, 0); 7806 NewSDValueDbgMsg(V, "Creating new node: ", this); 7807 return V; 7808 } 7809 7810 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7811 SDValue Val, SDValue Ptr, SDValue Mask, 7812 SDValue EVL, MachinePointerInfo PtrInfo, 7813 EVT SVT, Align Alignment, 7814 MachineMemOperand::Flags MMOFlags, 7815 const AAMDNodes &AAInfo, 7816 bool IsCompressing) { 7817 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7818 7819 MMOFlags |= MachineMemOperand::MOStore; 7820 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7821 7822 if (PtrInfo.V.isNull()) 7823 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7824 7825 MachineFunction &MF = getMachineFunction(); 7826 MachineMemOperand *MMO = MF.getMachineMemOperand( 7827 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7828 Alignment, AAInfo); 7829 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7830 IsCompressing); 7831 } 7832 7833 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7834 SDValue Val, SDValue Ptr, SDValue Mask, 7835 SDValue EVL, EVT SVT, 7836 MachineMemOperand *MMO, 7837 bool IsCompressing) { 7838 EVT VT = Val.getValueType(); 7839 7840 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7841 if (VT == SVT) 7842 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing); 7843 7844 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7845 "Should only be a truncating store, not extending!"); 7846 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7847 assert(VT.isVector() == SVT.isVector() && 7848 "Cannot use trunc store to convert to or from a vector!"); 7849 assert((!VT.isVector() || 7850 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7851 "Cannot use trunc store to change the number of vector elements!"); 7852 7853 SDVTList VTs = getVTList(MVT::Other); 7854 SDValue Undef = getUNDEF(Ptr.getValueType()); 7855 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7856 FoldingSetNodeID ID; 7857 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7858 ID.AddInteger(SVT.getRawBits()); 7859 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7860 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7861 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7862 void *IP = nullptr; 7863 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7864 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7865 return SDValue(E, 0); 7866 } 7867 auto *N = 7868 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7869 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7870 createOperands(N, Ops); 7871 7872 CSEMap.InsertNode(N, IP); 7873 InsertNode(N); 7874 SDValue V(N, 0); 7875 NewSDValueDbgMsg(V, "Creating new node: ", this); 7876 return V; 7877 } 7878 7879 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7880 SDValue Base, SDValue Offset, 7881 ISD::MemIndexedMode AM) { 7882 auto *ST = cast<VPStoreSDNode>(OrigStore); 7883 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7884 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7885 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7886 Offset, ST->getMask(), ST->getVectorLength()}; 7887 FoldingSetNodeID ID; 7888 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7889 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7890 ID.AddInteger(ST->getRawSubclassData()); 7891 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7892 void *IP = nullptr; 7893 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7894 return SDValue(E, 0); 7895 7896 auto *N = newSDNode<VPStoreSDNode>( 7897 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 7898 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 7899 createOperands(N, Ops); 7900 7901 CSEMap.InsertNode(N, IP); 7902 InsertNode(N); 7903 SDValue V(N, 0); 7904 NewSDValueDbgMsg(V, "Creating new node: ", this); 7905 return V; 7906 } 7907 7908 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7909 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 7910 ISD::MemIndexType IndexType) { 7911 assert(Ops.size() == 6 && "Incompatible number of operands"); 7912 7913 FoldingSetNodeID ID; 7914 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 7915 ID.AddInteger(VT.getRawBits()); 7916 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 7917 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7918 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7919 void *IP = nullptr; 7920 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7921 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 7922 return SDValue(E, 0); 7923 } 7924 7925 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7926 VT, MMO, IndexType); 7927 createOperands(N, Ops); 7928 7929 assert(N->getMask().getValueType().getVectorElementCount() == 7930 N->getValueType(0).getVectorElementCount() && 7931 "Vector width mismatch between mask and data"); 7932 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7933 N->getValueType(0).getVectorElementCount().isScalable() && 7934 "Scalable flags of index and data do not match"); 7935 assert(ElementCount::isKnownGE( 7936 N->getIndex().getValueType().getVectorElementCount(), 7937 N->getValueType(0).getVectorElementCount()) && 7938 "Vector width mismatch between index and data"); 7939 assert(isa<ConstantSDNode>(N->getScale()) && 7940 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7941 "Scale should be a constant power of 2"); 7942 7943 CSEMap.InsertNode(N, IP); 7944 InsertNode(N); 7945 SDValue V(N, 0); 7946 NewSDValueDbgMsg(V, "Creating new node: ", this); 7947 return V; 7948 } 7949 7950 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7951 ArrayRef<SDValue> Ops, 7952 MachineMemOperand *MMO, 7953 ISD::MemIndexType IndexType) { 7954 assert(Ops.size() == 7 && "Incompatible number of operands"); 7955 7956 FoldingSetNodeID ID; 7957 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 7958 ID.AddInteger(VT.getRawBits()); 7959 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 7960 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7961 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7962 void *IP = nullptr; 7963 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7964 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 7965 return SDValue(E, 0); 7966 } 7967 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7968 VT, MMO, IndexType); 7969 createOperands(N, Ops); 7970 7971 assert(N->getMask().getValueType().getVectorElementCount() == 7972 N->getValue().getValueType().getVectorElementCount() && 7973 "Vector width mismatch between mask and data"); 7974 assert( 7975 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7976 N->getValue().getValueType().getVectorElementCount().isScalable() && 7977 "Scalable flags of index and data do not match"); 7978 assert(ElementCount::isKnownGE( 7979 N->getIndex().getValueType().getVectorElementCount(), 7980 N->getValue().getValueType().getVectorElementCount()) && 7981 "Vector width mismatch between index and data"); 7982 assert(isa<ConstantSDNode>(N->getScale()) && 7983 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7984 "Scale should be a constant power of 2"); 7985 7986 CSEMap.InsertNode(N, IP); 7987 InsertNode(N); 7988 SDValue V(N, 0); 7989 NewSDValueDbgMsg(V, "Creating new node: ", this); 7990 return V; 7991 } 7992 7993 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7994 SDValue Base, SDValue Offset, SDValue Mask, 7995 SDValue PassThru, EVT MemVT, 7996 MachineMemOperand *MMO, 7997 ISD::MemIndexedMode AM, 7998 ISD::LoadExtType ExtTy, bool isExpanding) { 7999 bool Indexed = AM != ISD::UNINDEXED; 8000 assert((Indexed || Offset.isUndef()) && 8001 "Unindexed masked load with an offset!"); 8002 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8003 : getVTList(VT, MVT::Other); 8004 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8005 FoldingSetNodeID ID; 8006 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8007 ID.AddInteger(MemVT.getRawBits()); 8008 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8009 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8010 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8011 void *IP = nullptr; 8012 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8013 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8014 return SDValue(E, 0); 8015 } 8016 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8017 AM, ExtTy, isExpanding, MemVT, MMO); 8018 createOperands(N, Ops); 8019 8020 CSEMap.InsertNode(N, IP); 8021 InsertNode(N); 8022 SDValue V(N, 0); 8023 NewSDValueDbgMsg(V, "Creating new node: ", this); 8024 return V; 8025 } 8026 8027 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8028 SDValue Base, SDValue Offset, 8029 ISD::MemIndexedMode AM) { 8030 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8031 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8032 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8033 Offset, LD->getMask(), LD->getPassThru(), 8034 LD->getMemoryVT(), LD->getMemOperand(), AM, 8035 LD->getExtensionType(), LD->isExpandingLoad()); 8036 } 8037 8038 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8039 SDValue Val, SDValue Base, SDValue Offset, 8040 SDValue Mask, EVT MemVT, 8041 MachineMemOperand *MMO, 8042 ISD::MemIndexedMode AM, bool IsTruncating, 8043 bool IsCompressing) { 8044 assert(Chain.getValueType() == MVT::Other && 8045 "Invalid chain type"); 8046 bool Indexed = AM != ISD::UNINDEXED; 8047 assert((Indexed || Offset.isUndef()) && 8048 "Unindexed masked store with an offset!"); 8049 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8050 : getVTList(MVT::Other); 8051 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8052 FoldingSetNodeID ID; 8053 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8054 ID.AddInteger(MemVT.getRawBits()); 8055 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8056 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8057 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8058 void *IP = nullptr; 8059 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8060 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8061 return SDValue(E, 0); 8062 } 8063 auto *N = 8064 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8065 IsTruncating, IsCompressing, MemVT, MMO); 8066 createOperands(N, Ops); 8067 8068 CSEMap.InsertNode(N, IP); 8069 InsertNode(N); 8070 SDValue V(N, 0); 8071 NewSDValueDbgMsg(V, "Creating new node: ", this); 8072 return V; 8073 } 8074 8075 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8076 SDValue Base, SDValue Offset, 8077 ISD::MemIndexedMode AM) { 8078 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8079 assert(ST->getOffset().isUndef() && 8080 "Masked store is already a indexed store!"); 8081 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8082 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8083 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8084 } 8085 8086 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8087 ArrayRef<SDValue> Ops, 8088 MachineMemOperand *MMO, 8089 ISD::MemIndexType IndexType, 8090 ISD::LoadExtType ExtTy) { 8091 assert(Ops.size() == 6 && "Incompatible number of operands"); 8092 8093 FoldingSetNodeID ID; 8094 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8095 ID.AddInteger(MemVT.getRawBits()); 8096 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8097 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8098 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8099 void *IP = nullptr; 8100 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8101 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8102 return SDValue(E, 0); 8103 } 8104 8105 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8106 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8107 VTs, MemVT, MMO, IndexType, ExtTy); 8108 createOperands(N, Ops); 8109 8110 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8111 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8112 assert(N->getMask().getValueType().getVectorElementCount() == 8113 N->getValueType(0).getVectorElementCount() && 8114 "Vector width mismatch between mask and data"); 8115 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8116 N->getValueType(0).getVectorElementCount().isScalable() && 8117 "Scalable flags of index and data do not match"); 8118 assert(ElementCount::isKnownGE( 8119 N->getIndex().getValueType().getVectorElementCount(), 8120 N->getValueType(0).getVectorElementCount()) && 8121 "Vector width mismatch between index and data"); 8122 assert(isa<ConstantSDNode>(N->getScale()) && 8123 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8124 "Scale should be a constant power of 2"); 8125 8126 CSEMap.InsertNode(N, IP); 8127 InsertNode(N); 8128 SDValue V(N, 0); 8129 NewSDValueDbgMsg(V, "Creating new node: ", this); 8130 return V; 8131 } 8132 8133 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8134 ArrayRef<SDValue> Ops, 8135 MachineMemOperand *MMO, 8136 ISD::MemIndexType IndexType, 8137 bool IsTrunc) { 8138 assert(Ops.size() == 6 && "Incompatible number of operands"); 8139 8140 FoldingSetNodeID ID; 8141 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8142 ID.AddInteger(MemVT.getRawBits()); 8143 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8144 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8145 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8146 void *IP = nullptr; 8147 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8148 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8149 return SDValue(E, 0); 8150 } 8151 8152 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8153 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8154 VTs, MemVT, MMO, IndexType, IsTrunc); 8155 createOperands(N, Ops); 8156 8157 assert(N->getMask().getValueType().getVectorElementCount() == 8158 N->getValue().getValueType().getVectorElementCount() && 8159 "Vector width mismatch between mask and data"); 8160 assert( 8161 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8162 N->getValue().getValueType().getVectorElementCount().isScalable() && 8163 "Scalable flags of index and data do not match"); 8164 assert(ElementCount::isKnownGE( 8165 N->getIndex().getValueType().getVectorElementCount(), 8166 N->getValue().getValueType().getVectorElementCount()) && 8167 "Vector width mismatch between index and data"); 8168 assert(isa<ConstantSDNode>(N->getScale()) && 8169 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8170 "Scale should be a constant power of 2"); 8171 8172 CSEMap.InsertNode(N, IP); 8173 InsertNode(N); 8174 SDValue V(N, 0); 8175 NewSDValueDbgMsg(V, "Creating new node: ", this); 8176 return V; 8177 } 8178 8179 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8180 // select undef, T, F --> T (if T is a constant), otherwise F 8181 // select, ?, undef, F --> F 8182 // select, ?, T, undef --> T 8183 if (Cond.isUndef()) 8184 return isConstantValueOfAnyType(T) ? T : F; 8185 if (T.isUndef()) 8186 return F; 8187 if (F.isUndef()) 8188 return T; 8189 8190 // select true, T, F --> T 8191 // select false, T, F --> F 8192 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8193 return CondC->isZero() ? F : T; 8194 8195 // TODO: This should simplify VSELECT with constant condition using something 8196 // like this (but check boolean contents to be complete?): 8197 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8198 // return T; 8199 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8200 // return F; 8201 8202 // select ?, T, T --> T 8203 if (T == F) 8204 return T; 8205 8206 return SDValue(); 8207 } 8208 8209 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8210 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8211 if (X.isUndef()) 8212 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8213 // shift X, undef --> undef (because it may shift by the bitwidth) 8214 if (Y.isUndef()) 8215 return getUNDEF(X.getValueType()); 8216 8217 // shift 0, Y --> 0 8218 // shift X, 0 --> X 8219 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8220 return X; 8221 8222 // shift X, C >= bitwidth(X) --> undef 8223 // All vector elements must be too big (or undef) to avoid partial undefs. 8224 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8225 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8226 }; 8227 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8228 return getUNDEF(X.getValueType()); 8229 8230 return SDValue(); 8231 } 8232 8233 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8234 SDNodeFlags Flags) { 8235 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8236 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8237 // operation is poison. That result can be relaxed to undef. 8238 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8239 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8240 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8241 (YC && YC->getValueAPF().isNaN()); 8242 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8243 (YC && YC->getValueAPF().isInfinity()); 8244 8245 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8246 return getUNDEF(X.getValueType()); 8247 8248 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8249 return getUNDEF(X.getValueType()); 8250 8251 if (!YC) 8252 return SDValue(); 8253 8254 // X + -0.0 --> X 8255 if (Opcode == ISD::FADD) 8256 if (YC->getValueAPF().isNegZero()) 8257 return X; 8258 8259 // X - +0.0 --> X 8260 if (Opcode == ISD::FSUB) 8261 if (YC->getValueAPF().isPosZero()) 8262 return X; 8263 8264 // X * 1.0 --> X 8265 // X / 1.0 --> X 8266 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8267 if (YC->getValueAPF().isExactlyValue(1.0)) 8268 return X; 8269 8270 // X * 0.0 --> 0.0 8271 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8272 if (YC->getValueAPF().isZero()) 8273 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8274 8275 return SDValue(); 8276 } 8277 8278 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8279 SDValue Ptr, SDValue SV, unsigned Align) { 8280 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8281 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8282 } 8283 8284 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8285 ArrayRef<SDUse> Ops) { 8286 switch (Ops.size()) { 8287 case 0: return getNode(Opcode, DL, VT); 8288 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8289 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8290 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8291 default: break; 8292 } 8293 8294 // Copy from an SDUse array into an SDValue array for use with 8295 // the regular getNode logic. 8296 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8297 return getNode(Opcode, DL, VT, NewOps); 8298 } 8299 8300 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8301 ArrayRef<SDValue> Ops) { 8302 SDNodeFlags Flags; 8303 if (Inserter) 8304 Flags = Inserter->getFlags(); 8305 return getNode(Opcode, DL, VT, Ops, Flags); 8306 } 8307 8308 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8309 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8310 unsigned NumOps = Ops.size(); 8311 switch (NumOps) { 8312 case 0: return getNode(Opcode, DL, VT); 8313 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8314 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8315 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8316 default: break; 8317 } 8318 8319 #ifndef NDEBUG 8320 for (auto &Op : Ops) 8321 assert(Op.getOpcode() != ISD::DELETED_NODE && 8322 "Operand is DELETED_NODE!"); 8323 #endif 8324 8325 switch (Opcode) { 8326 default: break; 8327 case ISD::BUILD_VECTOR: 8328 // Attempt to simplify BUILD_VECTOR. 8329 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8330 return V; 8331 break; 8332 case ISD::CONCAT_VECTORS: 8333 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8334 return V; 8335 break; 8336 case ISD::SELECT_CC: 8337 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8338 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8339 "LHS and RHS of condition must have same type!"); 8340 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8341 "True and False arms of SelectCC must have same type!"); 8342 assert(Ops[2].getValueType() == VT && 8343 "select_cc node must be of same type as true and false value!"); 8344 break; 8345 case ISD::BR_CC: 8346 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8347 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8348 "LHS/RHS of comparison should match types!"); 8349 break; 8350 } 8351 8352 // Memoize nodes. 8353 SDNode *N; 8354 SDVTList VTs = getVTList(VT); 8355 8356 if (VT != MVT::Glue) { 8357 FoldingSetNodeID ID; 8358 AddNodeIDNode(ID, Opcode, VTs, Ops); 8359 void *IP = nullptr; 8360 8361 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8362 return SDValue(E, 0); 8363 8364 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8365 createOperands(N, Ops); 8366 8367 CSEMap.InsertNode(N, IP); 8368 } else { 8369 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8370 createOperands(N, Ops); 8371 } 8372 8373 N->setFlags(Flags); 8374 InsertNode(N); 8375 SDValue V(N, 0); 8376 NewSDValueDbgMsg(V, "Creating new node: ", this); 8377 return V; 8378 } 8379 8380 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8381 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8382 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8383 } 8384 8385 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8386 ArrayRef<SDValue> Ops) { 8387 SDNodeFlags Flags; 8388 if (Inserter) 8389 Flags = Inserter->getFlags(); 8390 return getNode(Opcode, DL, VTList, Ops, Flags); 8391 } 8392 8393 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8394 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8395 if (VTList.NumVTs == 1) 8396 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8397 8398 #ifndef NDEBUG 8399 for (auto &Op : Ops) 8400 assert(Op.getOpcode() != ISD::DELETED_NODE && 8401 "Operand is DELETED_NODE!"); 8402 #endif 8403 8404 switch (Opcode) { 8405 case ISD::STRICT_FP_EXTEND: 8406 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8407 "Invalid STRICT_FP_EXTEND!"); 8408 assert(VTList.VTs[0].isFloatingPoint() && 8409 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8410 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8411 "STRICT_FP_EXTEND result type should be vector iff the operand " 8412 "type is vector!"); 8413 assert((!VTList.VTs[0].isVector() || 8414 VTList.VTs[0].getVectorNumElements() == 8415 Ops[1].getValueType().getVectorNumElements()) && 8416 "Vector element count mismatch!"); 8417 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8418 "Invalid fpext node, dst <= src!"); 8419 break; 8420 case ISD::STRICT_FP_ROUND: 8421 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8422 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8423 "STRICT_FP_ROUND result type should be vector iff the operand " 8424 "type is vector!"); 8425 assert((!VTList.VTs[0].isVector() || 8426 VTList.VTs[0].getVectorNumElements() == 8427 Ops[1].getValueType().getVectorNumElements()) && 8428 "Vector element count mismatch!"); 8429 assert(VTList.VTs[0].isFloatingPoint() && 8430 Ops[1].getValueType().isFloatingPoint() && 8431 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8432 isa<ConstantSDNode>(Ops[2]) && 8433 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8434 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8435 "Invalid STRICT_FP_ROUND!"); 8436 break; 8437 #if 0 8438 // FIXME: figure out how to safely handle things like 8439 // int foo(int x) { return 1 << (x & 255); } 8440 // int bar() { return foo(256); } 8441 case ISD::SRA_PARTS: 8442 case ISD::SRL_PARTS: 8443 case ISD::SHL_PARTS: 8444 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8445 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8446 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8447 else if (N3.getOpcode() == ISD::AND) 8448 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8449 // If the and is only masking out bits that cannot effect the shift, 8450 // eliminate the and. 8451 unsigned NumBits = VT.getScalarSizeInBits()*2; 8452 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8453 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8454 } 8455 break; 8456 #endif 8457 } 8458 8459 // Memoize the node unless it returns a flag. 8460 SDNode *N; 8461 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8462 FoldingSetNodeID ID; 8463 AddNodeIDNode(ID, Opcode, VTList, Ops); 8464 void *IP = nullptr; 8465 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8466 return SDValue(E, 0); 8467 8468 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8469 createOperands(N, Ops); 8470 CSEMap.InsertNode(N, IP); 8471 } else { 8472 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8473 createOperands(N, Ops); 8474 } 8475 8476 N->setFlags(Flags); 8477 InsertNode(N); 8478 SDValue V(N, 0); 8479 NewSDValueDbgMsg(V, "Creating new node: ", this); 8480 return V; 8481 } 8482 8483 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8484 SDVTList VTList) { 8485 return getNode(Opcode, DL, VTList, None); 8486 } 8487 8488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8489 SDValue N1) { 8490 SDValue Ops[] = { N1 }; 8491 return getNode(Opcode, DL, VTList, Ops); 8492 } 8493 8494 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8495 SDValue N1, SDValue N2) { 8496 SDValue Ops[] = { N1, N2 }; 8497 return getNode(Opcode, DL, VTList, Ops); 8498 } 8499 8500 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8501 SDValue N1, SDValue N2, SDValue N3) { 8502 SDValue Ops[] = { N1, N2, N3 }; 8503 return getNode(Opcode, DL, VTList, Ops); 8504 } 8505 8506 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8507 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8508 SDValue Ops[] = { N1, N2, N3, N4 }; 8509 return getNode(Opcode, DL, VTList, Ops); 8510 } 8511 8512 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8513 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8514 SDValue N5) { 8515 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8516 return getNode(Opcode, DL, VTList, Ops); 8517 } 8518 8519 SDVTList SelectionDAG::getVTList(EVT VT) { 8520 return makeVTList(SDNode::getValueTypeList(VT), 1); 8521 } 8522 8523 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8524 FoldingSetNodeID ID; 8525 ID.AddInteger(2U); 8526 ID.AddInteger(VT1.getRawBits()); 8527 ID.AddInteger(VT2.getRawBits()); 8528 8529 void *IP = nullptr; 8530 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8531 if (!Result) { 8532 EVT *Array = Allocator.Allocate<EVT>(2); 8533 Array[0] = VT1; 8534 Array[1] = VT2; 8535 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8536 VTListMap.InsertNode(Result, IP); 8537 } 8538 return Result->getSDVTList(); 8539 } 8540 8541 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8542 FoldingSetNodeID ID; 8543 ID.AddInteger(3U); 8544 ID.AddInteger(VT1.getRawBits()); 8545 ID.AddInteger(VT2.getRawBits()); 8546 ID.AddInteger(VT3.getRawBits()); 8547 8548 void *IP = nullptr; 8549 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8550 if (!Result) { 8551 EVT *Array = Allocator.Allocate<EVT>(3); 8552 Array[0] = VT1; 8553 Array[1] = VT2; 8554 Array[2] = VT3; 8555 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8556 VTListMap.InsertNode(Result, IP); 8557 } 8558 return Result->getSDVTList(); 8559 } 8560 8561 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8562 FoldingSetNodeID ID; 8563 ID.AddInteger(4U); 8564 ID.AddInteger(VT1.getRawBits()); 8565 ID.AddInteger(VT2.getRawBits()); 8566 ID.AddInteger(VT3.getRawBits()); 8567 ID.AddInteger(VT4.getRawBits()); 8568 8569 void *IP = nullptr; 8570 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8571 if (!Result) { 8572 EVT *Array = Allocator.Allocate<EVT>(4); 8573 Array[0] = VT1; 8574 Array[1] = VT2; 8575 Array[2] = VT3; 8576 Array[3] = VT4; 8577 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8578 VTListMap.InsertNode(Result, IP); 8579 } 8580 return Result->getSDVTList(); 8581 } 8582 8583 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8584 unsigned NumVTs = VTs.size(); 8585 FoldingSetNodeID ID; 8586 ID.AddInteger(NumVTs); 8587 for (unsigned index = 0; index < NumVTs; index++) { 8588 ID.AddInteger(VTs[index].getRawBits()); 8589 } 8590 8591 void *IP = nullptr; 8592 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8593 if (!Result) { 8594 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8595 llvm::copy(VTs, Array); 8596 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8597 VTListMap.InsertNode(Result, IP); 8598 } 8599 return Result->getSDVTList(); 8600 } 8601 8602 8603 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8604 /// specified operands. If the resultant node already exists in the DAG, 8605 /// this does not modify the specified node, instead it returns the node that 8606 /// already exists. If the resultant node does not exist in the DAG, the 8607 /// input node is returned. As a degenerate case, if you specify the same 8608 /// input operands as the node already has, the input node is returned. 8609 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8610 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8611 8612 // Check to see if there is no change. 8613 if (Op == N->getOperand(0)) return N; 8614 8615 // See if the modified node already exists. 8616 void *InsertPos = nullptr; 8617 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8618 return Existing; 8619 8620 // Nope it doesn't. Remove the node from its current place in the maps. 8621 if (InsertPos) 8622 if (!RemoveNodeFromCSEMaps(N)) 8623 InsertPos = nullptr; 8624 8625 // Now we update the operands. 8626 N->OperandList[0].set(Op); 8627 8628 updateDivergence(N); 8629 // If this gets put into a CSE map, add it. 8630 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8631 return N; 8632 } 8633 8634 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8635 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8636 8637 // Check to see if there is no change. 8638 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8639 return N; // No operands changed, just return the input node. 8640 8641 // See if the modified node already exists. 8642 void *InsertPos = nullptr; 8643 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8644 return Existing; 8645 8646 // Nope it doesn't. Remove the node from its current place in the maps. 8647 if (InsertPos) 8648 if (!RemoveNodeFromCSEMaps(N)) 8649 InsertPos = nullptr; 8650 8651 // Now we update the operands. 8652 if (N->OperandList[0] != Op1) 8653 N->OperandList[0].set(Op1); 8654 if (N->OperandList[1] != Op2) 8655 N->OperandList[1].set(Op2); 8656 8657 updateDivergence(N); 8658 // If this gets put into a CSE map, add it. 8659 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8660 return N; 8661 } 8662 8663 SDNode *SelectionDAG:: 8664 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8665 SDValue Ops[] = { Op1, Op2, Op3 }; 8666 return UpdateNodeOperands(N, Ops); 8667 } 8668 8669 SDNode *SelectionDAG:: 8670 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8671 SDValue Op3, SDValue Op4) { 8672 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8673 return UpdateNodeOperands(N, Ops); 8674 } 8675 8676 SDNode *SelectionDAG:: 8677 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8678 SDValue Op3, SDValue Op4, SDValue Op5) { 8679 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8680 return UpdateNodeOperands(N, Ops); 8681 } 8682 8683 SDNode *SelectionDAG:: 8684 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8685 unsigned NumOps = Ops.size(); 8686 assert(N->getNumOperands() == NumOps && 8687 "Update with wrong number of operands"); 8688 8689 // If no operands changed just return the input node. 8690 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8691 return N; 8692 8693 // See if the modified node already exists. 8694 void *InsertPos = nullptr; 8695 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8696 return Existing; 8697 8698 // Nope it doesn't. Remove the node from its current place in the maps. 8699 if (InsertPos) 8700 if (!RemoveNodeFromCSEMaps(N)) 8701 InsertPos = nullptr; 8702 8703 // Now we update the operands. 8704 for (unsigned i = 0; i != NumOps; ++i) 8705 if (N->OperandList[i] != Ops[i]) 8706 N->OperandList[i].set(Ops[i]); 8707 8708 updateDivergence(N); 8709 // If this gets put into a CSE map, add it. 8710 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8711 return N; 8712 } 8713 8714 /// DropOperands - Release the operands and set this node to have 8715 /// zero operands. 8716 void SDNode::DropOperands() { 8717 // Unlike the code in MorphNodeTo that does this, we don't need to 8718 // watch for dead nodes here. 8719 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8720 SDUse &Use = *I++; 8721 Use.set(SDValue()); 8722 } 8723 } 8724 8725 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8726 ArrayRef<MachineMemOperand *> NewMemRefs) { 8727 if (NewMemRefs.empty()) { 8728 N->clearMemRefs(); 8729 return; 8730 } 8731 8732 // Check if we can avoid allocating by storing a single reference directly. 8733 if (NewMemRefs.size() == 1) { 8734 N->MemRefs = NewMemRefs[0]; 8735 N->NumMemRefs = 1; 8736 return; 8737 } 8738 8739 MachineMemOperand **MemRefsBuffer = 8740 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8741 llvm::copy(NewMemRefs, MemRefsBuffer); 8742 N->MemRefs = MemRefsBuffer; 8743 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8744 } 8745 8746 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8747 /// machine opcode. 8748 /// 8749 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8750 EVT VT) { 8751 SDVTList VTs = getVTList(VT); 8752 return SelectNodeTo(N, MachineOpc, VTs, None); 8753 } 8754 8755 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8756 EVT VT, SDValue Op1) { 8757 SDVTList VTs = getVTList(VT); 8758 SDValue Ops[] = { Op1 }; 8759 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8760 } 8761 8762 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8763 EVT VT, SDValue Op1, 8764 SDValue Op2) { 8765 SDVTList VTs = getVTList(VT); 8766 SDValue Ops[] = { Op1, Op2 }; 8767 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8768 } 8769 8770 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8771 EVT VT, SDValue Op1, 8772 SDValue Op2, SDValue Op3) { 8773 SDVTList VTs = getVTList(VT); 8774 SDValue Ops[] = { Op1, Op2, Op3 }; 8775 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8776 } 8777 8778 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8779 EVT VT, ArrayRef<SDValue> Ops) { 8780 SDVTList VTs = getVTList(VT); 8781 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8782 } 8783 8784 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8785 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8786 SDVTList VTs = getVTList(VT1, VT2); 8787 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8788 } 8789 8790 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8791 EVT VT1, EVT VT2) { 8792 SDVTList VTs = getVTList(VT1, VT2); 8793 return SelectNodeTo(N, MachineOpc, VTs, None); 8794 } 8795 8796 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8797 EVT VT1, EVT VT2, EVT VT3, 8798 ArrayRef<SDValue> Ops) { 8799 SDVTList VTs = getVTList(VT1, VT2, VT3); 8800 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8801 } 8802 8803 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8804 EVT VT1, EVT VT2, 8805 SDValue Op1, SDValue Op2) { 8806 SDVTList VTs = getVTList(VT1, VT2); 8807 SDValue Ops[] = { Op1, Op2 }; 8808 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8809 } 8810 8811 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8812 SDVTList VTs,ArrayRef<SDValue> Ops) { 8813 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8814 // Reset the NodeID to -1. 8815 New->setNodeId(-1); 8816 if (New != N) { 8817 ReplaceAllUsesWith(N, New); 8818 RemoveDeadNode(N); 8819 } 8820 return New; 8821 } 8822 8823 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8824 /// the line number information on the merged node since it is not possible to 8825 /// preserve the information that operation is associated with multiple lines. 8826 /// This will make the debugger working better at -O0, were there is a higher 8827 /// probability having other instructions associated with that line. 8828 /// 8829 /// For IROrder, we keep the smaller of the two 8830 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8831 DebugLoc NLoc = N->getDebugLoc(); 8832 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8833 N->setDebugLoc(DebugLoc()); 8834 } 8835 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8836 N->setIROrder(Order); 8837 return N; 8838 } 8839 8840 /// MorphNodeTo - This *mutates* the specified node to have the specified 8841 /// return type, opcode, and operands. 8842 /// 8843 /// Note that MorphNodeTo returns the resultant node. If there is already a 8844 /// node of the specified opcode and operands, it returns that node instead of 8845 /// the current one. Note that the SDLoc need not be the same. 8846 /// 8847 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8848 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8849 /// node, and because it doesn't require CSE recalculation for any of 8850 /// the node's users. 8851 /// 8852 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8853 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8854 /// the legalizer which maintain worklists that would need to be updated when 8855 /// deleting things. 8856 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8857 SDVTList VTs, ArrayRef<SDValue> Ops) { 8858 // If an identical node already exists, use it. 8859 void *IP = nullptr; 8860 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8861 FoldingSetNodeID ID; 8862 AddNodeIDNode(ID, Opc, VTs, Ops); 8863 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8864 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8865 } 8866 8867 if (!RemoveNodeFromCSEMaps(N)) 8868 IP = nullptr; 8869 8870 // Start the morphing. 8871 N->NodeType = Opc; 8872 N->ValueList = VTs.VTs; 8873 N->NumValues = VTs.NumVTs; 8874 8875 // Clear the operands list, updating used nodes to remove this from their 8876 // use list. Keep track of any operands that become dead as a result. 8877 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8878 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8879 SDUse &Use = *I++; 8880 SDNode *Used = Use.getNode(); 8881 Use.set(SDValue()); 8882 if (Used->use_empty()) 8883 DeadNodeSet.insert(Used); 8884 } 8885 8886 // For MachineNode, initialize the memory references information. 8887 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8888 MN->clearMemRefs(); 8889 8890 // Swap for an appropriately sized array from the recycler. 8891 removeOperands(N); 8892 createOperands(N, Ops); 8893 8894 // Delete any nodes that are still dead after adding the uses for the 8895 // new operands. 8896 if (!DeadNodeSet.empty()) { 8897 SmallVector<SDNode *, 16> DeadNodes; 8898 for (SDNode *N : DeadNodeSet) 8899 if (N->use_empty()) 8900 DeadNodes.push_back(N); 8901 RemoveDeadNodes(DeadNodes); 8902 } 8903 8904 if (IP) 8905 CSEMap.InsertNode(N, IP); // Memoize the new node. 8906 return N; 8907 } 8908 8909 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8910 unsigned OrigOpc = Node->getOpcode(); 8911 unsigned NewOpc; 8912 switch (OrigOpc) { 8913 default: 8914 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8915 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8916 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8917 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8918 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8919 #include "llvm/IR/ConstrainedOps.def" 8920 } 8921 8922 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8923 8924 // We're taking this node out of the chain, so we need to re-link things. 8925 SDValue InputChain = Node->getOperand(0); 8926 SDValue OutputChain = SDValue(Node, 1); 8927 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8928 8929 SmallVector<SDValue, 3> Ops; 8930 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8931 Ops.push_back(Node->getOperand(i)); 8932 8933 SDVTList VTs = getVTList(Node->getValueType(0)); 8934 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8935 8936 // MorphNodeTo can operate in two ways: if an existing node with the 8937 // specified operands exists, it can just return it. Otherwise, it 8938 // updates the node in place to have the requested operands. 8939 if (Res == Node) { 8940 // If we updated the node in place, reset the node ID. To the isel, 8941 // this should be just like a newly allocated machine node. 8942 Res->setNodeId(-1); 8943 } else { 8944 ReplaceAllUsesWith(Node, Res); 8945 RemoveDeadNode(Node); 8946 } 8947 8948 return Res; 8949 } 8950 8951 /// getMachineNode - These are used for target selectors to create a new node 8952 /// with specified return type(s), MachineInstr opcode, and operands. 8953 /// 8954 /// Note that getMachineNode returns the resultant node. If there is already a 8955 /// node of the specified opcode and operands, it returns that node instead of 8956 /// the current one. 8957 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8958 EVT VT) { 8959 SDVTList VTs = getVTList(VT); 8960 return getMachineNode(Opcode, dl, VTs, None); 8961 } 8962 8963 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8964 EVT VT, SDValue Op1) { 8965 SDVTList VTs = getVTList(VT); 8966 SDValue Ops[] = { Op1 }; 8967 return getMachineNode(Opcode, dl, VTs, Ops); 8968 } 8969 8970 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8971 EVT VT, SDValue Op1, SDValue Op2) { 8972 SDVTList VTs = getVTList(VT); 8973 SDValue Ops[] = { Op1, Op2 }; 8974 return getMachineNode(Opcode, dl, VTs, Ops); 8975 } 8976 8977 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8978 EVT VT, SDValue Op1, SDValue Op2, 8979 SDValue Op3) { 8980 SDVTList VTs = getVTList(VT); 8981 SDValue Ops[] = { Op1, Op2, Op3 }; 8982 return getMachineNode(Opcode, dl, VTs, Ops); 8983 } 8984 8985 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8986 EVT VT, ArrayRef<SDValue> Ops) { 8987 SDVTList VTs = getVTList(VT); 8988 return getMachineNode(Opcode, dl, VTs, Ops); 8989 } 8990 8991 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8992 EVT VT1, EVT VT2, SDValue Op1, 8993 SDValue Op2) { 8994 SDVTList VTs = getVTList(VT1, VT2); 8995 SDValue Ops[] = { Op1, Op2 }; 8996 return getMachineNode(Opcode, dl, VTs, Ops); 8997 } 8998 8999 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9000 EVT VT1, EVT VT2, SDValue Op1, 9001 SDValue Op2, SDValue Op3) { 9002 SDVTList VTs = getVTList(VT1, VT2); 9003 SDValue Ops[] = { Op1, Op2, Op3 }; 9004 return getMachineNode(Opcode, dl, VTs, Ops); 9005 } 9006 9007 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9008 EVT VT1, EVT VT2, 9009 ArrayRef<SDValue> Ops) { 9010 SDVTList VTs = getVTList(VT1, VT2); 9011 return getMachineNode(Opcode, dl, VTs, Ops); 9012 } 9013 9014 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9015 EVT VT1, EVT VT2, EVT VT3, 9016 SDValue Op1, SDValue Op2) { 9017 SDVTList VTs = getVTList(VT1, VT2, VT3); 9018 SDValue Ops[] = { Op1, Op2 }; 9019 return getMachineNode(Opcode, dl, VTs, Ops); 9020 } 9021 9022 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9023 EVT VT1, EVT VT2, EVT VT3, 9024 SDValue Op1, SDValue Op2, 9025 SDValue Op3) { 9026 SDVTList VTs = getVTList(VT1, VT2, VT3); 9027 SDValue Ops[] = { Op1, Op2, Op3 }; 9028 return getMachineNode(Opcode, dl, VTs, Ops); 9029 } 9030 9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9032 EVT VT1, EVT VT2, EVT VT3, 9033 ArrayRef<SDValue> Ops) { 9034 SDVTList VTs = getVTList(VT1, VT2, VT3); 9035 return getMachineNode(Opcode, dl, VTs, Ops); 9036 } 9037 9038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9039 ArrayRef<EVT> ResultTys, 9040 ArrayRef<SDValue> Ops) { 9041 SDVTList VTs = getVTList(ResultTys); 9042 return getMachineNode(Opcode, dl, VTs, Ops); 9043 } 9044 9045 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9046 SDVTList VTs, 9047 ArrayRef<SDValue> Ops) { 9048 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9049 MachineSDNode *N; 9050 void *IP = nullptr; 9051 9052 if (DoCSE) { 9053 FoldingSetNodeID ID; 9054 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9055 IP = nullptr; 9056 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9057 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9058 } 9059 } 9060 9061 // Allocate a new MachineSDNode. 9062 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9063 createOperands(N, Ops); 9064 9065 if (DoCSE) 9066 CSEMap.InsertNode(N, IP); 9067 9068 InsertNode(N); 9069 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9070 return N; 9071 } 9072 9073 /// getTargetExtractSubreg - A convenience function for creating 9074 /// TargetOpcode::EXTRACT_SUBREG nodes. 9075 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9076 SDValue Operand) { 9077 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9078 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9079 VT, Operand, SRIdxVal); 9080 return SDValue(Subreg, 0); 9081 } 9082 9083 /// getTargetInsertSubreg - A convenience function for creating 9084 /// TargetOpcode::INSERT_SUBREG nodes. 9085 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9086 SDValue Operand, SDValue Subreg) { 9087 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9088 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9089 VT, Operand, Subreg, SRIdxVal); 9090 return SDValue(Result, 0); 9091 } 9092 9093 /// getNodeIfExists - Get the specified node if it's already available, or 9094 /// else return NULL. 9095 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9096 ArrayRef<SDValue> Ops) { 9097 SDNodeFlags Flags; 9098 if (Inserter) 9099 Flags = Inserter->getFlags(); 9100 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9101 } 9102 9103 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9104 ArrayRef<SDValue> Ops, 9105 const SDNodeFlags Flags) { 9106 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9107 FoldingSetNodeID ID; 9108 AddNodeIDNode(ID, Opcode, VTList, Ops); 9109 void *IP = nullptr; 9110 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9111 E->intersectFlagsWith(Flags); 9112 return E; 9113 } 9114 } 9115 return nullptr; 9116 } 9117 9118 /// doesNodeExist - Check if a node exists without modifying its flags. 9119 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9120 ArrayRef<SDValue> Ops) { 9121 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9122 FoldingSetNodeID ID; 9123 AddNodeIDNode(ID, Opcode, VTList, Ops); 9124 void *IP = nullptr; 9125 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9126 return true; 9127 } 9128 return false; 9129 } 9130 9131 /// getDbgValue - Creates a SDDbgValue node. 9132 /// 9133 /// SDNode 9134 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9135 SDNode *N, unsigned R, bool IsIndirect, 9136 const DebugLoc &DL, unsigned O) { 9137 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9138 "Expected inlined-at fields to agree"); 9139 return new (DbgInfo->getAlloc()) 9140 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9141 {}, IsIndirect, DL, O, 9142 /*IsVariadic=*/false); 9143 } 9144 9145 /// Constant 9146 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9147 DIExpression *Expr, 9148 const Value *C, 9149 const DebugLoc &DL, unsigned O) { 9150 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9151 "Expected inlined-at fields to agree"); 9152 return new (DbgInfo->getAlloc()) 9153 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9154 /*IsIndirect=*/false, DL, O, 9155 /*IsVariadic=*/false); 9156 } 9157 9158 /// FrameIndex 9159 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9160 DIExpression *Expr, unsigned FI, 9161 bool IsIndirect, 9162 const DebugLoc &DL, 9163 unsigned O) { 9164 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9165 "Expected inlined-at fields to agree"); 9166 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9167 } 9168 9169 /// FrameIndex with dependencies 9170 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9171 DIExpression *Expr, unsigned FI, 9172 ArrayRef<SDNode *> Dependencies, 9173 bool IsIndirect, 9174 const DebugLoc &DL, 9175 unsigned O) { 9176 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9177 "Expected inlined-at fields to agree"); 9178 return new (DbgInfo->getAlloc()) 9179 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9180 Dependencies, IsIndirect, DL, O, 9181 /*IsVariadic=*/false); 9182 } 9183 9184 /// VReg 9185 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9186 unsigned VReg, bool IsIndirect, 9187 const DebugLoc &DL, unsigned O) { 9188 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9189 "Expected inlined-at fields to agree"); 9190 return new (DbgInfo->getAlloc()) 9191 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9192 {}, IsIndirect, DL, O, 9193 /*IsVariadic=*/false); 9194 } 9195 9196 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9197 ArrayRef<SDDbgOperand> Locs, 9198 ArrayRef<SDNode *> Dependencies, 9199 bool IsIndirect, const DebugLoc &DL, 9200 unsigned O, bool IsVariadic) { 9201 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9202 "Expected inlined-at fields to agree"); 9203 return new (DbgInfo->getAlloc()) 9204 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9205 DL, O, IsVariadic); 9206 } 9207 9208 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9209 unsigned OffsetInBits, unsigned SizeInBits, 9210 bool InvalidateDbg) { 9211 SDNode *FromNode = From.getNode(); 9212 SDNode *ToNode = To.getNode(); 9213 assert(FromNode && ToNode && "Can't modify dbg values"); 9214 9215 // PR35338 9216 // TODO: assert(From != To && "Redundant dbg value transfer"); 9217 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9218 if (From == To || FromNode == ToNode) 9219 return; 9220 9221 if (!FromNode->getHasDebugValue()) 9222 return; 9223 9224 SDDbgOperand FromLocOp = 9225 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9226 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9227 9228 SmallVector<SDDbgValue *, 2> ClonedDVs; 9229 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9230 if (Dbg->isInvalidated()) 9231 continue; 9232 9233 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9234 9235 // Create a new location ops vector that is equal to the old vector, but 9236 // with each instance of FromLocOp replaced with ToLocOp. 9237 bool Changed = false; 9238 auto NewLocOps = Dbg->copyLocationOps(); 9239 std::replace_if( 9240 NewLocOps.begin(), NewLocOps.end(), 9241 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9242 bool Match = Op == FromLocOp; 9243 Changed |= Match; 9244 return Match; 9245 }, 9246 ToLocOp); 9247 // Ignore this SDDbgValue if we didn't find a matching location. 9248 if (!Changed) 9249 continue; 9250 9251 DIVariable *Var = Dbg->getVariable(); 9252 auto *Expr = Dbg->getExpression(); 9253 // If a fragment is requested, update the expression. 9254 if (SizeInBits) { 9255 // When splitting a larger (e.g., sign-extended) value whose 9256 // lower bits are described with an SDDbgValue, do not attempt 9257 // to transfer the SDDbgValue to the upper bits. 9258 if (auto FI = Expr->getFragmentInfo()) 9259 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9260 continue; 9261 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9262 SizeInBits); 9263 if (!Fragment) 9264 continue; 9265 Expr = *Fragment; 9266 } 9267 9268 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9269 // Clone the SDDbgValue and move it to To. 9270 SDDbgValue *Clone = getDbgValueList( 9271 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9272 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9273 Dbg->isVariadic()); 9274 ClonedDVs.push_back(Clone); 9275 9276 if (InvalidateDbg) { 9277 // Invalidate value and indicate the SDDbgValue should not be emitted. 9278 Dbg->setIsInvalidated(); 9279 Dbg->setIsEmitted(); 9280 } 9281 } 9282 9283 for (SDDbgValue *Dbg : ClonedDVs) { 9284 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9285 "Transferred DbgValues should depend on the new SDNode"); 9286 AddDbgValue(Dbg, false); 9287 } 9288 } 9289 9290 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9291 if (!N.getHasDebugValue()) 9292 return; 9293 9294 SmallVector<SDDbgValue *, 2> ClonedDVs; 9295 for (auto DV : GetDbgValues(&N)) { 9296 if (DV->isInvalidated()) 9297 continue; 9298 switch (N.getOpcode()) { 9299 default: 9300 break; 9301 case ISD::ADD: 9302 SDValue N0 = N.getOperand(0); 9303 SDValue N1 = N.getOperand(1); 9304 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9305 isConstantIntBuildVectorOrConstantInt(N1)) { 9306 uint64_t Offset = N.getConstantOperandVal(1); 9307 9308 // Rewrite an ADD constant node into a DIExpression. Since we are 9309 // performing arithmetic to compute the variable's *value* in the 9310 // DIExpression, we need to mark the expression with a 9311 // DW_OP_stack_value. 9312 auto *DIExpr = DV->getExpression(); 9313 auto NewLocOps = DV->copyLocationOps(); 9314 bool Changed = false; 9315 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9316 // We're not given a ResNo to compare against because the whole 9317 // node is going away. We know that any ISD::ADD only has one 9318 // result, so we can assume any node match is using the result. 9319 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9320 NewLocOps[i].getSDNode() != &N) 9321 continue; 9322 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9323 SmallVector<uint64_t, 3> ExprOps; 9324 DIExpression::appendOffset(ExprOps, Offset); 9325 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9326 Changed = true; 9327 } 9328 (void)Changed; 9329 assert(Changed && "Salvage target doesn't use N"); 9330 9331 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9332 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9333 NewLocOps, AdditionalDependencies, 9334 DV->isIndirect(), DV->getDebugLoc(), 9335 DV->getOrder(), DV->isVariadic()); 9336 ClonedDVs.push_back(Clone); 9337 DV->setIsInvalidated(); 9338 DV->setIsEmitted(); 9339 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9340 N0.getNode()->dumprFull(this); 9341 dbgs() << " into " << *DIExpr << '\n'); 9342 } 9343 } 9344 } 9345 9346 for (SDDbgValue *Dbg : ClonedDVs) { 9347 assert(!Dbg->getSDNodes().empty() && 9348 "Salvaged DbgValue should depend on a new SDNode"); 9349 AddDbgValue(Dbg, false); 9350 } 9351 } 9352 9353 /// Creates a SDDbgLabel node. 9354 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9355 const DebugLoc &DL, unsigned O) { 9356 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9357 "Expected inlined-at fields to agree"); 9358 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9359 } 9360 9361 namespace { 9362 9363 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9364 /// pointed to by a use iterator is deleted, increment the use iterator 9365 /// so that it doesn't dangle. 9366 /// 9367 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9368 SDNode::use_iterator &UI; 9369 SDNode::use_iterator &UE; 9370 9371 void NodeDeleted(SDNode *N, SDNode *E) override { 9372 // Increment the iterator as needed. 9373 while (UI != UE && N == *UI) 9374 ++UI; 9375 } 9376 9377 public: 9378 RAUWUpdateListener(SelectionDAG &d, 9379 SDNode::use_iterator &ui, 9380 SDNode::use_iterator &ue) 9381 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9382 }; 9383 9384 } // end anonymous namespace 9385 9386 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9387 /// This can cause recursive merging of nodes in the DAG. 9388 /// 9389 /// This version assumes From has a single result value. 9390 /// 9391 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9392 SDNode *From = FromN.getNode(); 9393 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9394 "Cannot replace with this method!"); 9395 assert(From != To.getNode() && "Cannot replace uses of with self"); 9396 9397 // Preserve Debug Values 9398 transferDbgValues(FromN, To); 9399 9400 // Iterate over all the existing uses of From. New uses will be added 9401 // to the beginning of the use list, which we avoid visiting. 9402 // This specifically avoids visiting uses of From that arise while the 9403 // replacement is happening, because any such uses would be the result 9404 // of CSE: If an existing node looks like From after one of its operands 9405 // is replaced by To, we don't want to replace of all its users with To 9406 // too. See PR3018 for more info. 9407 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9408 RAUWUpdateListener Listener(*this, UI, UE); 9409 while (UI != UE) { 9410 SDNode *User = *UI; 9411 9412 // This node is about to morph, remove its old self from the CSE maps. 9413 RemoveNodeFromCSEMaps(User); 9414 9415 // A user can appear in a use list multiple times, and when this 9416 // happens the uses are usually next to each other in the list. 9417 // To help reduce the number of CSE recomputations, process all 9418 // the uses of this user that we can find this way. 9419 do { 9420 SDUse &Use = UI.getUse(); 9421 ++UI; 9422 Use.set(To); 9423 if (To->isDivergent() != From->isDivergent()) 9424 updateDivergence(User); 9425 } while (UI != UE && *UI == User); 9426 // Now that we have modified User, add it back to the CSE maps. If it 9427 // already exists there, recursively merge the results together. 9428 AddModifiedNodeToCSEMaps(User); 9429 } 9430 9431 // If we just RAUW'd the root, take note. 9432 if (FromN == getRoot()) 9433 setRoot(To); 9434 } 9435 9436 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9437 /// This can cause recursive merging of nodes in the DAG. 9438 /// 9439 /// This version assumes that for each value of From, there is a 9440 /// corresponding value in To in the same position with the same type. 9441 /// 9442 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9443 #ifndef NDEBUG 9444 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9445 assert((!From->hasAnyUseOfValue(i) || 9446 From->getValueType(i) == To->getValueType(i)) && 9447 "Cannot use this version of ReplaceAllUsesWith!"); 9448 #endif 9449 9450 // Handle the trivial case. 9451 if (From == To) 9452 return; 9453 9454 // Preserve Debug Info. Only do this if there's a use. 9455 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9456 if (From->hasAnyUseOfValue(i)) { 9457 assert((i < To->getNumValues()) && "Invalid To location"); 9458 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9459 } 9460 9461 // Iterate over just the existing users of From. See the comments in 9462 // the ReplaceAllUsesWith above. 9463 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9464 RAUWUpdateListener Listener(*this, UI, UE); 9465 while (UI != UE) { 9466 SDNode *User = *UI; 9467 9468 // This node is about to morph, remove its old self from the CSE maps. 9469 RemoveNodeFromCSEMaps(User); 9470 9471 // A user can appear in a use list multiple times, and when this 9472 // happens the uses are usually next to each other in the list. 9473 // To help reduce the number of CSE recomputations, process all 9474 // the uses of this user that we can find this way. 9475 do { 9476 SDUse &Use = UI.getUse(); 9477 ++UI; 9478 Use.setNode(To); 9479 if (To->isDivergent() != From->isDivergent()) 9480 updateDivergence(User); 9481 } while (UI != UE && *UI == User); 9482 9483 // Now that we have modified User, add it back to the CSE maps. If it 9484 // already exists there, recursively merge the results together. 9485 AddModifiedNodeToCSEMaps(User); 9486 } 9487 9488 // If we just RAUW'd the root, take note. 9489 if (From == getRoot().getNode()) 9490 setRoot(SDValue(To, getRoot().getResNo())); 9491 } 9492 9493 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9494 /// This can cause recursive merging of nodes in the DAG. 9495 /// 9496 /// This version can replace From with any result values. To must match the 9497 /// number and types of values returned by From. 9498 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9499 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9500 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9501 9502 // Preserve Debug Info. 9503 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9504 transferDbgValues(SDValue(From, i), To[i]); 9505 9506 // Iterate over just the existing users of From. See the comments in 9507 // the ReplaceAllUsesWith above. 9508 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9509 RAUWUpdateListener Listener(*this, UI, UE); 9510 while (UI != UE) { 9511 SDNode *User = *UI; 9512 9513 // This node is about to morph, remove its old self from the CSE maps. 9514 RemoveNodeFromCSEMaps(User); 9515 9516 // A user can appear in a use list multiple times, and when this happens the 9517 // uses are usually next to each other in the list. To help reduce the 9518 // number of CSE and divergence recomputations, process all the uses of this 9519 // user that we can find this way. 9520 bool To_IsDivergent = false; 9521 do { 9522 SDUse &Use = UI.getUse(); 9523 const SDValue &ToOp = To[Use.getResNo()]; 9524 ++UI; 9525 Use.set(ToOp); 9526 To_IsDivergent |= ToOp->isDivergent(); 9527 } while (UI != UE && *UI == User); 9528 9529 if (To_IsDivergent != From->isDivergent()) 9530 updateDivergence(User); 9531 9532 // Now that we have modified User, add it back to the CSE maps. If it 9533 // already exists there, recursively merge the results together. 9534 AddModifiedNodeToCSEMaps(User); 9535 } 9536 9537 // If we just RAUW'd the root, take note. 9538 if (From == getRoot().getNode()) 9539 setRoot(SDValue(To[getRoot().getResNo()])); 9540 } 9541 9542 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9543 /// uses of other values produced by From.getNode() alone. The Deleted 9544 /// vector is handled the same way as for ReplaceAllUsesWith. 9545 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9546 // Handle the really simple, really trivial case efficiently. 9547 if (From == To) return; 9548 9549 // Handle the simple, trivial, case efficiently. 9550 if (From.getNode()->getNumValues() == 1) { 9551 ReplaceAllUsesWith(From, To); 9552 return; 9553 } 9554 9555 // Preserve Debug Info. 9556 transferDbgValues(From, To); 9557 9558 // Iterate over just the existing users of From. See the comments in 9559 // the ReplaceAllUsesWith above. 9560 SDNode::use_iterator UI = From.getNode()->use_begin(), 9561 UE = From.getNode()->use_end(); 9562 RAUWUpdateListener Listener(*this, UI, UE); 9563 while (UI != UE) { 9564 SDNode *User = *UI; 9565 bool UserRemovedFromCSEMaps = false; 9566 9567 // A user can appear in a use list multiple times, and when this 9568 // happens the uses are usually next to each other in the list. 9569 // To help reduce the number of CSE recomputations, process all 9570 // the uses of this user that we can find this way. 9571 do { 9572 SDUse &Use = UI.getUse(); 9573 9574 // Skip uses of different values from the same node. 9575 if (Use.getResNo() != From.getResNo()) { 9576 ++UI; 9577 continue; 9578 } 9579 9580 // If this node hasn't been modified yet, it's still in the CSE maps, 9581 // so remove its old self from the CSE maps. 9582 if (!UserRemovedFromCSEMaps) { 9583 RemoveNodeFromCSEMaps(User); 9584 UserRemovedFromCSEMaps = true; 9585 } 9586 9587 ++UI; 9588 Use.set(To); 9589 if (To->isDivergent() != From->isDivergent()) 9590 updateDivergence(User); 9591 } while (UI != UE && *UI == User); 9592 // We are iterating over all uses of the From node, so if a use 9593 // doesn't use the specific value, no changes are made. 9594 if (!UserRemovedFromCSEMaps) 9595 continue; 9596 9597 // Now that we have modified User, add it back to the CSE maps. If it 9598 // already exists there, recursively merge the results together. 9599 AddModifiedNodeToCSEMaps(User); 9600 } 9601 9602 // If we just RAUW'd the root, take note. 9603 if (From == getRoot()) 9604 setRoot(To); 9605 } 9606 9607 namespace { 9608 9609 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9610 /// to record information about a use. 9611 struct UseMemo { 9612 SDNode *User; 9613 unsigned Index; 9614 SDUse *Use; 9615 }; 9616 9617 /// operator< - Sort Memos by User. 9618 bool operator<(const UseMemo &L, const UseMemo &R) { 9619 return (intptr_t)L.User < (intptr_t)R.User; 9620 } 9621 9622 } // end anonymous namespace 9623 9624 bool SelectionDAG::calculateDivergence(SDNode *N) { 9625 if (TLI->isSDNodeAlwaysUniform(N)) { 9626 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9627 "Conflicting divergence information!"); 9628 return false; 9629 } 9630 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9631 return true; 9632 for (auto &Op : N->ops()) { 9633 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9634 return true; 9635 } 9636 return false; 9637 } 9638 9639 void SelectionDAG::updateDivergence(SDNode *N) { 9640 SmallVector<SDNode *, 16> Worklist(1, N); 9641 do { 9642 N = Worklist.pop_back_val(); 9643 bool IsDivergent = calculateDivergence(N); 9644 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9645 N->SDNodeBits.IsDivergent = IsDivergent; 9646 llvm::append_range(Worklist, N->uses()); 9647 } 9648 } while (!Worklist.empty()); 9649 } 9650 9651 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9652 DenseMap<SDNode *, unsigned> Degree; 9653 Order.reserve(AllNodes.size()); 9654 for (auto &N : allnodes()) { 9655 unsigned NOps = N.getNumOperands(); 9656 Degree[&N] = NOps; 9657 if (0 == NOps) 9658 Order.push_back(&N); 9659 } 9660 for (size_t I = 0; I != Order.size(); ++I) { 9661 SDNode *N = Order[I]; 9662 for (auto U : N->uses()) { 9663 unsigned &UnsortedOps = Degree[U]; 9664 if (0 == --UnsortedOps) 9665 Order.push_back(U); 9666 } 9667 } 9668 } 9669 9670 #ifndef NDEBUG 9671 void SelectionDAG::VerifyDAGDivergence() { 9672 std::vector<SDNode *> TopoOrder; 9673 CreateTopologicalOrder(TopoOrder); 9674 for (auto *N : TopoOrder) { 9675 assert(calculateDivergence(N) == N->isDivergent() && 9676 "Divergence bit inconsistency detected"); 9677 } 9678 } 9679 #endif 9680 9681 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9682 /// uses of other values produced by From.getNode() alone. The same value 9683 /// may appear in both the From and To list. The Deleted vector is 9684 /// handled the same way as for ReplaceAllUsesWith. 9685 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9686 const SDValue *To, 9687 unsigned Num){ 9688 // Handle the simple, trivial case efficiently. 9689 if (Num == 1) 9690 return ReplaceAllUsesOfValueWith(*From, *To); 9691 9692 transferDbgValues(*From, *To); 9693 9694 // Read up all the uses and make records of them. This helps 9695 // processing new uses that are introduced during the 9696 // replacement process. 9697 SmallVector<UseMemo, 4> Uses; 9698 for (unsigned i = 0; i != Num; ++i) { 9699 unsigned FromResNo = From[i].getResNo(); 9700 SDNode *FromNode = From[i].getNode(); 9701 for (SDNode::use_iterator UI = FromNode->use_begin(), 9702 E = FromNode->use_end(); UI != E; ++UI) { 9703 SDUse &Use = UI.getUse(); 9704 if (Use.getResNo() == FromResNo) { 9705 UseMemo Memo = { *UI, i, &Use }; 9706 Uses.push_back(Memo); 9707 } 9708 } 9709 } 9710 9711 // Sort the uses, so that all the uses from a given User are together. 9712 llvm::sort(Uses); 9713 9714 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9715 UseIndex != UseIndexEnd; ) { 9716 // We know that this user uses some value of From. If it is the right 9717 // value, update it. 9718 SDNode *User = Uses[UseIndex].User; 9719 9720 // This node is about to morph, remove its old self from the CSE maps. 9721 RemoveNodeFromCSEMaps(User); 9722 9723 // The Uses array is sorted, so all the uses for a given User 9724 // are next to each other in the list. 9725 // To help reduce the number of CSE recomputations, process all 9726 // the uses of this user that we can find this way. 9727 do { 9728 unsigned i = Uses[UseIndex].Index; 9729 SDUse &Use = *Uses[UseIndex].Use; 9730 ++UseIndex; 9731 9732 Use.set(To[i]); 9733 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9734 9735 // Now that we have modified User, add it back to the CSE maps. If it 9736 // already exists there, recursively merge the results together. 9737 AddModifiedNodeToCSEMaps(User); 9738 } 9739 } 9740 9741 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9742 /// based on their topological order. It returns the maximum id and a vector 9743 /// of the SDNodes* in assigned order by reference. 9744 unsigned SelectionDAG::AssignTopologicalOrder() { 9745 unsigned DAGSize = 0; 9746 9747 // SortedPos tracks the progress of the algorithm. Nodes before it are 9748 // sorted, nodes after it are unsorted. When the algorithm completes 9749 // it is at the end of the list. 9750 allnodes_iterator SortedPos = allnodes_begin(); 9751 9752 // Visit all the nodes. Move nodes with no operands to the front of 9753 // the list immediately. Annotate nodes that do have operands with their 9754 // operand count. Before we do this, the Node Id fields of the nodes 9755 // may contain arbitrary values. After, the Node Id fields for nodes 9756 // before SortedPos will contain the topological sort index, and the 9757 // Node Id fields for nodes At SortedPos and after will contain the 9758 // count of outstanding operands. 9759 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 9760 checkForCycles(&N, this); 9761 unsigned Degree = N.getNumOperands(); 9762 if (Degree == 0) { 9763 // A node with no uses, add it to the result array immediately. 9764 N.setNodeId(DAGSize++); 9765 allnodes_iterator Q(&N); 9766 if (Q != SortedPos) 9767 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9768 assert(SortedPos != AllNodes.end() && "Overran node list"); 9769 ++SortedPos; 9770 } else { 9771 // Temporarily use the Node Id as scratch space for the degree count. 9772 N.setNodeId(Degree); 9773 } 9774 } 9775 9776 // Visit all the nodes. As we iterate, move nodes into sorted order, 9777 // such that by the time the end is reached all nodes will be sorted. 9778 for (SDNode &Node : allnodes()) { 9779 SDNode *N = &Node; 9780 checkForCycles(N, this); 9781 // N is in sorted position, so all its uses have one less operand 9782 // that needs to be sorted. 9783 for (SDNode *P : N->uses()) { 9784 unsigned Degree = P->getNodeId(); 9785 assert(Degree != 0 && "Invalid node degree"); 9786 --Degree; 9787 if (Degree == 0) { 9788 // All of P's operands are sorted, so P may sorted now. 9789 P->setNodeId(DAGSize++); 9790 if (P->getIterator() != SortedPos) 9791 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9792 assert(SortedPos != AllNodes.end() && "Overran node list"); 9793 ++SortedPos; 9794 } else { 9795 // Update P's outstanding operand count. 9796 P->setNodeId(Degree); 9797 } 9798 } 9799 if (Node.getIterator() == SortedPos) { 9800 #ifndef NDEBUG 9801 allnodes_iterator I(N); 9802 SDNode *S = &*++I; 9803 dbgs() << "Overran sorted position:\n"; 9804 S->dumprFull(this); dbgs() << "\n"; 9805 dbgs() << "Checking if this is due to cycles\n"; 9806 checkForCycles(this, true); 9807 #endif 9808 llvm_unreachable(nullptr); 9809 } 9810 } 9811 9812 assert(SortedPos == AllNodes.end() && 9813 "Topological sort incomplete!"); 9814 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9815 "First node in topological sort is not the entry token!"); 9816 assert(AllNodes.front().getNodeId() == 0 && 9817 "First node in topological sort has non-zero id!"); 9818 assert(AllNodes.front().getNumOperands() == 0 && 9819 "First node in topological sort has operands!"); 9820 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9821 "Last node in topologic sort has unexpected id!"); 9822 assert(AllNodes.back().use_empty() && 9823 "Last node in topologic sort has users!"); 9824 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9825 return DAGSize; 9826 } 9827 9828 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9829 /// value is produced by SD. 9830 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9831 for (SDNode *SD : DB->getSDNodes()) { 9832 if (!SD) 9833 continue; 9834 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9835 SD->setHasDebugValue(true); 9836 } 9837 DbgInfo->add(DB, isParameter); 9838 } 9839 9840 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9841 9842 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9843 SDValue NewMemOpChain) { 9844 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9845 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9846 // The new memory operation must have the same position as the old load in 9847 // terms of memory dependency. Create a TokenFactor for the old load and new 9848 // memory operation and update uses of the old load's output chain to use that 9849 // TokenFactor. 9850 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9851 return NewMemOpChain; 9852 9853 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9854 OldChain, NewMemOpChain); 9855 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9856 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9857 return TokenFactor; 9858 } 9859 9860 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9861 SDValue NewMemOp) { 9862 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9863 SDValue OldChain = SDValue(OldLoad, 1); 9864 SDValue NewMemOpChain = NewMemOp.getValue(1); 9865 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9866 } 9867 9868 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9869 Function **OutFunction) { 9870 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9871 9872 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9873 auto *Module = MF->getFunction().getParent(); 9874 auto *Function = Module->getFunction(Symbol); 9875 9876 if (OutFunction != nullptr) 9877 *OutFunction = Function; 9878 9879 if (Function != nullptr) { 9880 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9881 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9882 } 9883 9884 std::string ErrorStr; 9885 raw_string_ostream ErrorFormatter(ErrorStr); 9886 ErrorFormatter << "Undefined external symbol "; 9887 ErrorFormatter << '"' << Symbol << '"'; 9888 report_fatal_error(Twine(ErrorFormatter.str())); 9889 } 9890 9891 //===----------------------------------------------------------------------===// 9892 // SDNode Class 9893 //===----------------------------------------------------------------------===// 9894 9895 bool llvm::isNullConstant(SDValue V) { 9896 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9897 return Const != nullptr && Const->isZero(); 9898 } 9899 9900 bool llvm::isNullFPConstant(SDValue V) { 9901 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9902 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9903 } 9904 9905 bool llvm::isAllOnesConstant(SDValue V) { 9906 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9907 return Const != nullptr && Const->isAllOnes(); 9908 } 9909 9910 bool llvm::isOneConstant(SDValue V) { 9911 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9912 return Const != nullptr && Const->isOne(); 9913 } 9914 9915 SDValue llvm::peekThroughBitcasts(SDValue V) { 9916 while (V.getOpcode() == ISD::BITCAST) 9917 V = V.getOperand(0); 9918 return V; 9919 } 9920 9921 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9922 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9923 V = V.getOperand(0); 9924 return V; 9925 } 9926 9927 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9928 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9929 V = V.getOperand(0); 9930 return V; 9931 } 9932 9933 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9934 if (V.getOpcode() != ISD::XOR) 9935 return false; 9936 V = peekThroughBitcasts(V.getOperand(1)); 9937 unsigned NumBits = V.getScalarValueSizeInBits(); 9938 ConstantSDNode *C = 9939 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9940 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9941 } 9942 9943 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9944 bool AllowTruncation) { 9945 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9946 return CN; 9947 9948 // SplatVectors can truncate their operands. Ignore that case here unless 9949 // AllowTruncation is set. 9950 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9951 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9952 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9953 EVT CVT = CN->getValueType(0); 9954 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9955 if (AllowTruncation || CVT == VecEltVT) 9956 return CN; 9957 } 9958 } 9959 9960 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9961 BitVector UndefElements; 9962 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9963 9964 // BuildVectors can truncate their operands. Ignore that case here unless 9965 // AllowTruncation is set. 9966 if (CN && (UndefElements.none() || AllowUndefs)) { 9967 EVT CVT = CN->getValueType(0); 9968 EVT NSVT = N.getValueType().getScalarType(); 9969 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9970 if (AllowTruncation || (CVT == NSVT)) 9971 return CN; 9972 } 9973 } 9974 9975 return nullptr; 9976 } 9977 9978 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9979 bool AllowUndefs, 9980 bool AllowTruncation) { 9981 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9982 return CN; 9983 9984 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9985 BitVector UndefElements; 9986 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9987 9988 // BuildVectors can truncate their operands. Ignore that case here unless 9989 // AllowTruncation is set. 9990 if (CN && (UndefElements.none() || AllowUndefs)) { 9991 EVT CVT = CN->getValueType(0); 9992 EVT NSVT = N.getValueType().getScalarType(); 9993 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9994 if (AllowTruncation || (CVT == NSVT)) 9995 return CN; 9996 } 9997 } 9998 9999 return nullptr; 10000 } 10001 10002 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10003 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10004 return CN; 10005 10006 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10007 BitVector UndefElements; 10008 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10009 if (CN && (UndefElements.none() || AllowUndefs)) 10010 return CN; 10011 } 10012 10013 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10014 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10015 return CN; 10016 10017 return nullptr; 10018 } 10019 10020 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10021 const APInt &DemandedElts, 10022 bool AllowUndefs) { 10023 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10024 return CN; 10025 10026 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10027 BitVector UndefElements; 10028 ConstantFPSDNode *CN = 10029 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10030 if (CN && (UndefElements.none() || AllowUndefs)) 10031 return CN; 10032 } 10033 10034 return nullptr; 10035 } 10036 10037 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10038 // TODO: may want to use peekThroughBitcast() here. 10039 ConstantSDNode *C = 10040 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10041 return C && C->isZero(); 10042 } 10043 10044 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10045 // TODO: may want to use peekThroughBitcast() here. 10046 unsigned BitWidth = N.getScalarValueSizeInBits(); 10047 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10048 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10049 } 10050 10051 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10052 N = peekThroughBitcasts(N); 10053 unsigned BitWidth = N.getScalarValueSizeInBits(); 10054 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10055 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10056 } 10057 10058 HandleSDNode::~HandleSDNode() { 10059 DropOperands(); 10060 } 10061 10062 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10063 const DebugLoc &DL, 10064 const GlobalValue *GA, EVT VT, 10065 int64_t o, unsigned TF) 10066 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10067 TheGlobal = GA; 10068 } 10069 10070 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10071 EVT VT, unsigned SrcAS, 10072 unsigned DestAS) 10073 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10074 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10075 10076 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10077 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10078 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10079 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10080 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10081 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10082 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10083 10084 // We check here that the size of the memory operand fits within the size of 10085 // the MMO. This is because the MMO might indicate only a possible address 10086 // range instead of specifying the affected memory addresses precisely. 10087 // TODO: Make MachineMemOperands aware of scalable vectors. 10088 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10089 "Size mismatch!"); 10090 } 10091 10092 /// Profile - Gather unique data for the node. 10093 /// 10094 void SDNode::Profile(FoldingSetNodeID &ID) const { 10095 AddNodeIDNode(ID, this); 10096 } 10097 10098 namespace { 10099 10100 struct EVTArray { 10101 std::vector<EVT> VTs; 10102 10103 EVTArray() { 10104 VTs.reserve(MVT::VALUETYPE_SIZE); 10105 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10106 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10107 } 10108 }; 10109 10110 } // end anonymous namespace 10111 10112 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10113 static ManagedStatic<EVTArray> SimpleVTArray; 10114 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10115 10116 /// getValueTypeList - Return a pointer to the specified value type. 10117 /// 10118 const EVT *SDNode::getValueTypeList(EVT VT) { 10119 if (VT.isExtended()) { 10120 sys::SmartScopedLock<true> Lock(*VTMutex); 10121 return &(*EVTs->insert(VT).first); 10122 } 10123 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10124 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10125 } 10126 10127 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10128 /// indicated value. This method ignores uses of other values defined by this 10129 /// operation. 10130 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10131 assert(Value < getNumValues() && "Bad value!"); 10132 10133 // TODO: Only iterate over uses of a given value of the node 10134 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10135 if (UI.getUse().getResNo() == Value) { 10136 if (NUses == 0) 10137 return false; 10138 --NUses; 10139 } 10140 } 10141 10142 // Found exactly the right number of uses? 10143 return NUses == 0; 10144 } 10145 10146 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10147 /// value. This method ignores uses of other values defined by this operation. 10148 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10149 assert(Value < getNumValues() && "Bad value!"); 10150 10151 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10152 if (UI.getUse().getResNo() == Value) 10153 return true; 10154 10155 return false; 10156 } 10157 10158 /// isOnlyUserOf - Return true if this node is the only use of N. 10159 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10160 bool Seen = false; 10161 for (const SDNode *User : N->uses()) { 10162 if (User == this) 10163 Seen = true; 10164 else 10165 return false; 10166 } 10167 10168 return Seen; 10169 } 10170 10171 /// Return true if the only users of N are contained in Nodes. 10172 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10173 bool Seen = false; 10174 for (const SDNode *User : N->uses()) { 10175 if (llvm::is_contained(Nodes, User)) 10176 Seen = true; 10177 else 10178 return false; 10179 } 10180 10181 return Seen; 10182 } 10183 10184 /// isOperand - Return true if this node is an operand of N. 10185 bool SDValue::isOperandOf(const SDNode *N) const { 10186 return is_contained(N->op_values(), *this); 10187 } 10188 10189 bool SDNode::isOperandOf(const SDNode *N) const { 10190 return any_of(N->op_values(), 10191 [this](SDValue Op) { return this == Op.getNode(); }); 10192 } 10193 10194 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10195 /// be a chain) reaches the specified operand without crossing any 10196 /// side-effecting instructions on any chain path. In practice, this looks 10197 /// through token factors and non-volatile loads. In order to remain efficient, 10198 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10199 /// 10200 /// Note that we only need to examine chains when we're searching for 10201 /// side-effects; SelectionDAG requires that all side-effects are represented 10202 /// by chains, even if another operand would force a specific ordering. This 10203 /// constraint is necessary to allow transformations like splitting loads. 10204 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10205 unsigned Depth) const { 10206 if (*this == Dest) return true; 10207 10208 // Don't search too deeply, we just want to be able to see through 10209 // TokenFactor's etc. 10210 if (Depth == 0) return false; 10211 10212 // If this is a token factor, all inputs to the TF happen in parallel. 10213 if (getOpcode() == ISD::TokenFactor) { 10214 // First, try a shallow search. 10215 if (is_contained((*this)->ops(), Dest)) { 10216 // We found the chain we want as an operand of this TokenFactor. 10217 // Essentially, we reach the chain without side-effects if we could 10218 // serialize the TokenFactor into a simple chain of operations with 10219 // Dest as the last operation. This is automatically true if the 10220 // chain has one use: there are no other ordering constraints. 10221 // If the chain has more than one use, we give up: some other 10222 // use of Dest might force a side-effect between Dest and the current 10223 // node. 10224 if (Dest.hasOneUse()) 10225 return true; 10226 } 10227 // Next, try a deep search: check whether every operand of the TokenFactor 10228 // reaches Dest. 10229 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10230 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10231 }); 10232 } 10233 10234 // Loads don't have side effects, look through them. 10235 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10236 if (Ld->isUnordered()) 10237 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10238 } 10239 return false; 10240 } 10241 10242 bool SDNode::hasPredecessor(const SDNode *N) const { 10243 SmallPtrSet<const SDNode *, 32> Visited; 10244 SmallVector<const SDNode *, 16> Worklist; 10245 Worklist.push_back(this); 10246 return hasPredecessorHelper(N, Visited, Worklist); 10247 } 10248 10249 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10250 this->Flags.intersectWith(Flags); 10251 } 10252 10253 SDValue 10254 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10255 ArrayRef<ISD::NodeType> CandidateBinOps, 10256 bool AllowPartials) { 10257 // The pattern must end in an extract from index 0. 10258 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10259 !isNullConstant(Extract->getOperand(1))) 10260 return SDValue(); 10261 10262 // Match against one of the candidate binary ops. 10263 SDValue Op = Extract->getOperand(0); 10264 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10265 return Op.getOpcode() == unsigned(BinOp); 10266 })) 10267 return SDValue(); 10268 10269 // Floating-point reductions may require relaxed constraints on the final step 10270 // of the reduction because they may reorder intermediate operations. 10271 unsigned CandidateBinOp = Op.getOpcode(); 10272 if (Op.getValueType().isFloatingPoint()) { 10273 SDNodeFlags Flags = Op->getFlags(); 10274 switch (CandidateBinOp) { 10275 case ISD::FADD: 10276 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10277 return SDValue(); 10278 break; 10279 default: 10280 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10281 } 10282 } 10283 10284 // Matching failed - attempt to see if we did enough stages that a partial 10285 // reduction from a subvector is possible. 10286 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10287 if (!AllowPartials || !Op) 10288 return SDValue(); 10289 EVT OpVT = Op.getValueType(); 10290 EVT OpSVT = OpVT.getScalarType(); 10291 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10292 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10293 return SDValue(); 10294 BinOp = (ISD::NodeType)CandidateBinOp; 10295 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10296 getVectorIdxConstant(0, SDLoc(Op))); 10297 }; 10298 10299 // At each stage, we're looking for something that looks like: 10300 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10301 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10302 // i32 undef, i32 undef, i32 undef, i32 undef> 10303 // %a = binop <8 x i32> %op, %s 10304 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10305 // we expect something like: 10306 // <4,5,6,7,u,u,u,u> 10307 // <2,3,u,u,u,u,u,u> 10308 // <1,u,u,u,u,u,u,u> 10309 // While a partial reduction match would be: 10310 // <2,3,u,u,u,u,u,u> 10311 // <1,u,u,u,u,u,u,u> 10312 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10313 SDValue PrevOp; 10314 for (unsigned i = 0; i < Stages; ++i) { 10315 unsigned MaskEnd = (1 << i); 10316 10317 if (Op.getOpcode() != CandidateBinOp) 10318 return PartialReduction(PrevOp, MaskEnd); 10319 10320 SDValue Op0 = Op.getOperand(0); 10321 SDValue Op1 = Op.getOperand(1); 10322 10323 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10324 if (Shuffle) { 10325 Op = Op1; 10326 } else { 10327 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10328 Op = Op0; 10329 } 10330 10331 // The first operand of the shuffle should be the same as the other operand 10332 // of the binop. 10333 if (!Shuffle || Shuffle->getOperand(0) != Op) 10334 return PartialReduction(PrevOp, MaskEnd); 10335 10336 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10337 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10338 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10339 return PartialReduction(PrevOp, MaskEnd); 10340 10341 PrevOp = Op; 10342 } 10343 10344 // Handle subvector reductions, which tend to appear after the shuffle 10345 // reduction stages. 10346 while (Op.getOpcode() == CandidateBinOp) { 10347 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10348 SDValue Op0 = Op.getOperand(0); 10349 SDValue Op1 = Op.getOperand(1); 10350 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10351 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10352 Op0.getOperand(0) != Op1.getOperand(0)) 10353 break; 10354 SDValue Src = Op0.getOperand(0); 10355 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10356 if (NumSrcElts != (2 * NumElts)) 10357 break; 10358 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10359 Op1.getConstantOperandAPInt(1) == NumElts) && 10360 !(Op1.getConstantOperandAPInt(1) == 0 && 10361 Op0.getConstantOperandAPInt(1) == NumElts)) 10362 break; 10363 Op = Src; 10364 } 10365 10366 BinOp = (ISD::NodeType)CandidateBinOp; 10367 return Op; 10368 } 10369 10370 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10371 assert(N->getNumValues() == 1 && 10372 "Can't unroll a vector with multiple results!"); 10373 10374 EVT VT = N->getValueType(0); 10375 unsigned NE = VT.getVectorNumElements(); 10376 EVT EltVT = VT.getVectorElementType(); 10377 SDLoc dl(N); 10378 10379 SmallVector<SDValue, 8> Scalars; 10380 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10381 10382 // If ResNE is 0, fully unroll the vector op. 10383 if (ResNE == 0) 10384 ResNE = NE; 10385 else if (NE > ResNE) 10386 NE = ResNE; 10387 10388 unsigned i; 10389 for (i= 0; i != NE; ++i) { 10390 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10391 SDValue Operand = N->getOperand(j); 10392 EVT OperandVT = Operand.getValueType(); 10393 if (OperandVT.isVector()) { 10394 // A vector operand; extract a single element. 10395 EVT OperandEltVT = OperandVT.getVectorElementType(); 10396 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10397 Operand, getVectorIdxConstant(i, dl)); 10398 } else { 10399 // A scalar operand; just use it as is. 10400 Operands[j] = Operand; 10401 } 10402 } 10403 10404 switch (N->getOpcode()) { 10405 default: { 10406 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10407 N->getFlags())); 10408 break; 10409 } 10410 case ISD::VSELECT: 10411 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10412 break; 10413 case ISD::SHL: 10414 case ISD::SRA: 10415 case ISD::SRL: 10416 case ISD::ROTL: 10417 case ISD::ROTR: 10418 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10419 getShiftAmountOperand(Operands[0].getValueType(), 10420 Operands[1]))); 10421 break; 10422 case ISD::SIGN_EXTEND_INREG: { 10423 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10424 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10425 Operands[0], 10426 getValueType(ExtVT))); 10427 } 10428 } 10429 } 10430 10431 for (; i < ResNE; ++i) 10432 Scalars.push_back(getUNDEF(EltVT)); 10433 10434 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10435 return getBuildVector(VecVT, dl, Scalars); 10436 } 10437 10438 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10439 SDNode *N, unsigned ResNE) { 10440 unsigned Opcode = N->getOpcode(); 10441 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10442 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10443 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10444 "Expected an overflow opcode"); 10445 10446 EVT ResVT = N->getValueType(0); 10447 EVT OvVT = N->getValueType(1); 10448 EVT ResEltVT = ResVT.getVectorElementType(); 10449 EVT OvEltVT = OvVT.getVectorElementType(); 10450 SDLoc dl(N); 10451 10452 // If ResNE is 0, fully unroll the vector op. 10453 unsigned NE = ResVT.getVectorNumElements(); 10454 if (ResNE == 0) 10455 ResNE = NE; 10456 else if (NE > ResNE) 10457 NE = ResNE; 10458 10459 SmallVector<SDValue, 8> LHSScalars; 10460 SmallVector<SDValue, 8> RHSScalars; 10461 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10462 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10463 10464 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10465 SDVTList VTs = getVTList(ResEltVT, SVT); 10466 SmallVector<SDValue, 8> ResScalars; 10467 SmallVector<SDValue, 8> OvScalars; 10468 for (unsigned i = 0; i < NE; ++i) { 10469 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10470 SDValue Ov = 10471 getSelect(dl, OvEltVT, Res.getValue(1), 10472 getBoolConstant(true, dl, OvEltVT, ResVT), 10473 getConstant(0, dl, OvEltVT)); 10474 10475 ResScalars.push_back(Res); 10476 OvScalars.push_back(Ov); 10477 } 10478 10479 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10480 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10481 10482 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10483 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10484 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10485 getBuildVector(NewOvVT, dl, OvScalars)); 10486 } 10487 10488 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10489 LoadSDNode *Base, 10490 unsigned Bytes, 10491 int Dist) const { 10492 if (LD->isVolatile() || Base->isVolatile()) 10493 return false; 10494 // TODO: probably too restrictive for atomics, revisit 10495 if (!LD->isSimple()) 10496 return false; 10497 if (LD->isIndexed() || Base->isIndexed()) 10498 return false; 10499 if (LD->getChain() != Base->getChain()) 10500 return false; 10501 EVT VT = LD->getValueType(0); 10502 if (VT.getSizeInBits() / 8 != Bytes) 10503 return false; 10504 10505 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10506 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10507 10508 int64_t Offset = 0; 10509 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10510 return (Dist * Bytes == Offset); 10511 return false; 10512 } 10513 10514 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10515 /// if it cannot be inferred. 10516 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10517 // If this is a GlobalAddress + cst, return the alignment. 10518 const GlobalValue *GV = nullptr; 10519 int64_t GVOffset = 0; 10520 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10521 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10522 KnownBits Known(PtrWidth); 10523 llvm::computeKnownBits(GV, Known, getDataLayout()); 10524 unsigned AlignBits = Known.countMinTrailingZeros(); 10525 if (AlignBits) 10526 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10527 } 10528 10529 // If this is a direct reference to a stack slot, use information about the 10530 // stack slot's alignment. 10531 int FrameIdx = INT_MIN; 10532 int64_t FrameOffset = 0; 10533 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10534 FrameIdx = FI->getIndex(); 10535 } else if (isBaseWithConstantOffset(Ptr) && 10536 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10537 // Handle FI+Cst 10538 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10539 FrameOffset = Ptr.getConstantOperandVal(1); 10540 } 10541 10542 if (FrameIdx != INT_MIN) { 10543 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10544 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10545 } 10546 10547 return None; 10548 } 10549 10550 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10551 /// which is split (or expanded) into two not necessarily identical pieces. 10552 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10553 // Currently all types are split in half. 10554 EVT LoVT, HiVT; 10555 if (!VT.isVector()) 10556 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10557 else 10558 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10559 10560 return std::make_pair(LoVT, HiVT); 10561 } 10562 10563 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10564 /// type, dependent on an enveloping VT that has been split into two identical 10565 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10566 std::pair<EVT, EVT> 10567 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10568 bool *HiIsEmpty) const { 10569 EVT EltTp = VT.getVectorElementType(); 10570 // Examples: 10571 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10572 // custom VL=9 with enveloping VL=8/8 yields 8/1 10573 // custom VL=10 with enveloping VL=8/8 yields 8/2 10574 // etc. 10575 ElementCount VTNumElts = VT.getVectorElementCount(); 10576 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10577 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10578 "Mixing fixed width and scalable vectors when enveloping a type"); 10579 EVT LoVT, HiVT; 10580 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10581 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10582 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10583 *HiIsEmpty = false; 10584 } else { 10585 // Flag that hi type has zero storage size, but return split envelop type 10586 // (this would be easier if vector types with zero elements were allowed). 10587 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10588 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10589 *HiIsEmpty = true; 10590 } 10591 return std::make_pair(LoVT, HiVT); 10592 } 10593 10594 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10595 /// low/high part. 10596 std::pair<SDValue, SDValue> 10597 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10598 const EVT &HiVT) { 10599 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10600 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10601 "Splitting vector with an invalid mixture of fixed and scalable " 10602 "vector types"); 10603 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10604 N.getValueType().getVectorMinNumElements() && 10605 "More vector elements requested than available!"); 10606 SDValue Lo, Hi; 10607 Lo = 10608 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10609 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10610 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10611 // IDX with the runtime scaling factor of the result vector type. For 10612 // fixed-width result vectors, that runtime scaling factor is 1. 10613 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10614 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10615 return std::make_pair(Lo, Hi); 10616 } 10617 10618 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10619 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10620 EVT VT = N.getValueType(); 10621 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10622 NextPowerOf2(VT.getVectorNumElements())); 10623 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10624 getVectorIdxConstant(0, DL)); 10625 } 10626 10627 void SelectionDAG::ExtractVectorElements(SDValue Op, 10628 SmallVectorImpl<SDValue> &Args, 10629 unsigned Start, unsigned Count, 10630 EVT EltVT) { 10631 EVT VT = Op.getValueType(); 10632 if (Count == 0) 10633 Count = VT.getVectorNumElements(); 10634 if (EltVT == EVT()) 10635 EltVT = VT.getVectorElementType(); 10636 SDLoc SL(Op); 10637 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10638 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10639 getVectorIdxConstant(i, SL))); 10640 } 10641 } 10642 10643 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10644 unsigned GlobalAddressSDNode::getAddressSpace() const { 10645 return getGlobal()->getType()->getAddressSpace(); 10646 } 10647 10648 Type *ConstantPoolSDNode::getType() const { 10649 if (isMachineConstantPoolEntry()) 10650 return Val.MachineCPVal->getType(); 10651 return Val.ConstVal->getType(); 10652 } 10653 10654 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10655 unsigned &SplatBitSize, 10656 bool &HasAnyUndefs, 10657 unsigned MinSplatBits, 10658 bool IsBigEndian) const { 10659 EVT VT = getValueType(0); 10660 assert(VT.isVector() && "Expected a vector type"); 10661 unsigned VecWidth = VT.getSizeInBits(); 10662 if (MinSplatBits > VecWidth) 10663 return false; 10664 10665 // FIXME: The widths are based on this node's type, but build vectors can 10666 // truncate their operands. 10667 SplatValue = APInt(VecWidth, 0); 10668 SplatUndef = APInt(VecWidth, 0); 10669 10670 // Get the bits. Bits with undefined values (when the corresponding element 10671 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10672 // in SplatValue. If any of the values are not constant, give up and return 10673 // false. 10674 unsigned int NumOps = getNumOperands(); 10675 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10676 unsigned EltWidth = VT.getScalarSizeInBits(); 10677 10678 for (unsigned j = 0; j < NumOps; ++j) { 10679 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10680 SDValue OpVal = getOperand(i); 10681 unsigned BitPos = j * EltWidth; 10682 10683 if (OpVal.isUndef()) 10684 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10685 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10686 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10687 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10688 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10689 else 10690 return false; 10691 } 10692 10693 // The build_vector is all constants or undefs. Find the smallest element 10694 // size that splats the vector. 10695 HasAnyUndefs = (SplatUndef != 0); 10696 10697 // FIXME: This does not work for vectors with elements less than 8 bits. 10698 while (VecWidth > 8) { 10699 unsigned HalfSize = VecWidth / 2; 10700 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10701 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10702 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10703 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10704 10705 // If the two halves do not match (ignoring undef bits), stop here. 10706 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10707 MinSplatBits > HalfSize) 10708 break; 10709 10710 SplatValue = HighValue | LowValue; 10711 SplatUndef = HighUndef & LowUndef; 10712 10713 VecWidth = HalfSize; 10714 } 10715 10716 SplatBitSize = VecWidth; 10717 return true; 10718 } 10719 10720 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10721 BitVector *UndefElements) const { 10722 unsigned NumOps = getNumOperands(); 10723 if (UndefElements) { 10724 UndefElements->clear(); 10725 UndefElements->resize(NumOps); 10726 } 10727 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10728 if (!DemandedElts) 10729 return SDValue(); 10730 SDValue Splatted; 10731 for (unsigned i = 0; i != NumOps; ++i) { 10732 if (!DemandedElts[i]) 10733 continue; 10734 SDValue Op = getOperand(i); 10735 if (Op.isUndef()) { 10736 if (UndefElements) 10737 (*UndefElements)[i] = true; 10738 } else if (!Splatted) { 10739 Splatted = Op; 10740 } else if (Splatted != Op) { 10741 return SDValue(); 10742 } 10743 } 10744 10745 if (!Splatted) { 10746 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10747 assert(getOperand(FirstDemandedIdx).isUndef() && 10748 "Can only have a splat without a constant for all undefs."); 10749 return getOperand(FirstDemandedIdx); 10750 } 10751 10752 return Splatted; 10753 } 10754 10755 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10756 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10757 return getSplatValue(DemandedElts, UndefElements); 10758 } 10759 10760 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10761 SmallVectorImpl<SDValue> &Sequence, 10762 BitVector *UndefElements) const { 10763 unsigned NumOps = getNumOperands(); 10764 Sequence.clear(); 10765 if (UndefElements) { 10766 UndefElements->clear(); 10767 UndefElements->resize(NumOps); 10768 } 10769 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10770 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10771 return false; 10772 10773 // Set the undefs even if we don't find a sequence (like getSplatValue). 10774 if (UndefElements) 10775 for (unsigned I = 0; I != NumOps; ++I) 10776 if (DemandedElts[I] && getOperand(I).isUndef()) 10777 (*UndefElements)[I] = true; 10778 10779 // Iteratively widen the sequence length looking for repetitions. 10780 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10781 Sequence.append(SeqLen, SDValue()); 10782 for (unsigned I = 0; I != NumOps; ++I) { 10783 if (!DemandedElts[I]) 10784 continue; 10785 SDValue &SeqOp = Sequence[I % SeqLen]; 10786 SDValue Op = getOperand(I); 10787 if (Op.isUndef()) { 10788 if (!SeqOp) 10789 SeqOp = Op; 10790 continue; 10791 } 10792 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10793 Sequence.clear(); 10794 break; 10795 } 10796 SeqOp = Op; 10797 } 10798 if (!Sequence.empty()) 10799 return true; 10800 } 10801 10802 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10803 return false; 10804 } 10805 10806 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10807 BitVector *UndefElements) const { 10808 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10809 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10810 } 10811 10812 ConstantSDNode * 10813 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10814 BitVector *UndefElements) const { 10815 return dyn_cast_or_null<ConstantSDNode>( 10816 getSplatValue(DemandedElts, UndefElements)); 10817 } 10818 10819 ConstantSDNode * 10820 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10821 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10822 } 10823 10824 ConstantFPSDNode * 10825 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10826 BitVector *UndefElements) const { 10827 return dyn_cast_or_null<ConstantFPSDNode>( 10828 getSplatValue(DemandedElts, UndefElements)); 10829 } 10830 10831 ConstantFPSDNode * 10832 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10833 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10834 } 10835 10836 int32_t 10837 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10838 uint32_t BitWidth) const { 10839 if (ConstantFPSDNode *CN = 10840 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10841 bool IsExact; 10842 APSInt IntVal(BitWidth); 10843 const APFloat &APF = CN->getValueAPF(); 10844 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10845 APFloat::opOK || 10846 !IsExact) 10847 return -1; 10848 10849 return IntVal.exactLogBase2(); 10850 } 10851 return -1; 10852 } 10853 10854 bool BuildVectorSDNode::getConstantRawBits( 10855 bool IsLittleEndian, unsigned DstEltSizeInBits, 10856 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 10857 // Early-out if this contains anything but Undef/Constant/ConstantFP. 10858 if (!isConstant()) 10859 return false; 10860 10861 unsigned NumSrcOps = getNumOperands(); 10862 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 10863 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10864 "Invalid bitcast scale"); 10865 10866 // Extract raw src bits. 10867 SmallVector<APInt> SrcBitElements(NumSrcOps, 10868 APInt::getNullValue(SrcEltSizeInBits)); 10869 BitVector SrcUndeElements(NumSrcOps, false); 10870 10871 for (unsigned I = 0; I != NumSrcOps; ++I) { 10872 SDValue Op = getOperand(I); 10873 if (Op.isUndef()) { 10874 SrcUndeElements.set(I); 10875 continue; 10876 } 10877 auto *CInt = dyn_cast<ConstantSDNode>(Op); 10878 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 10879 assert((CInt || CFP) && "Unknown constant"); 10880 SrcBitElements[I] = 10881 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 10882 : CFP->getValueAPF().bitcastToAPInt(); 10883 } 10884 10885 // Recast to dst width. 10886 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 10887 SrcBitElements, UndefElements, SrcUndeElements); 10888 return true; 10889 } 10890 10891 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 10892 unsigned DstEltSizeInBits, 10893 SmallVectorImpl<APInt> &DstBitElements, 10894 ArrayRef<APInt> SrcBitElements, 10895 BitVector &DstUndefElements, 10896 const BitVector &SrcUndefElements) { 10897 unsigned NumSrcOps = SrcBitElements.size(); 10898 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 10899 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10900 "Invalid bitcast scale"); 10901 assert(NumSrcOps == SrcUndefElements.size() && 10902 "Vector size mismatch"); 10903 10904 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 10905 DstUndefElements.clear(); 10906 DstUndefElements.resize(NumDstOps, false); 10907 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 10908 10909 // Concatenate src elements constant bits together into dst element. 10910 if (SrcEltSizeInBits <= DstEltSizeInBits) { 10911 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 10912 for (unsigned I = 0; I != NumDstOps; ++I) { 10913 DstUndefElements.set(I); 10914 APInt &DstBits = DstBitElements[I]; 10915 for (unsigned J = 0; J != Scale; ++J) { 10916 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 10917 if (SrcUndefElements[Idx]) 10918 continue; 10919 DstUndefElements.reset(I); 10920 const APInt &SrcBits = SrcBitElements[Idx]; 10921 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 10922 "Illegal constant bitwidths"); 10923 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 10924 } 10925 } 10926 return; 10927 } 10928 10929 // Split src element constant bits into dst elements. 10930 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 10931 for (unsigned I = 0; I != NumSrcOps; ++I) { 10932 if (SrcUndefElements[I]) { 10933 DstUndefElements.set(I * Scale, (I + 1) * Scale); 10934 continue; 10935 } 10936 const APInt &SrcBits = SrcBitElements[I]; 10937 for (unsigned J = 0; J != Scale; ++J) { 10938 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 10939 APInt &DstBits = DstBitElements[Idx]; 10940 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 10941 } 10942 } 10943 } 10944 10945 bool BuildVectorSDNode::isConstant() const { 10946 for (const SDValue &Op : op_values()) { 10947 unsigned Opc = Op.getOpcode(); 10948 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10949 return false; 10950 } 10951 return true; 10952 } 10953 10954 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10955 // Find the first non-undef value in the shuffle mask. 10956 unsigned i, e; 10957 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10958 /* search */; 10959 10960 // If all elements are undefined, this shuffle can be considered a splat 10961 // (although it should eventually get simplified away completely). 10962 if (i == e) 10963 return true; 10964 10965 // Make sure all remaining elements are either undef or the same as the first 10966 // non-undef value. 10967 for (int Idx = Mask[i]; i != e; ++i) 10968 if (Mask[i] >= 0 && Mask[i] != Idx) 10969 return false; 10970 return true; 10971 } 10972 10973 // Returns the SDNode if it is a constant integer BuildVector 10974 // or constant integer. 10975 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10976 if (isa<ConstantSDNode>(N)) 10977 return N.getNode(); 10978 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10979 return N.getNode(); 10980 // Treat a GlobalAddress supporting constant offset folding as a 10981 // constant integer. 10982 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10983 if (GA->getOpcode() == ISD::GlobalAddress && 10984 TLI->isOffsetFoldingLegal(GA)) 10985 return GA; 10986 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10987 isa<ConstantSDNode>(N.getOperand(0))) 10988 return N.getNode(); 10989 return nullptr; 10990 } 10991 10992 // Returns the SDNode if it is a constant float BuildVector 10993 // or constant float. 10994 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10995 if (isa<ConstantFPSDNode>(N)) 10996 return N.getNode(); 10997 10998 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10999 return N.getNode(); 11000 11001 return nullptr; 11002 } 11003 11004 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11005 assert(!Node->OperandList && "Node already has operands"); 11006 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11007 "too many operands to fit into SDNode"); 11008 SDUse *Ops = OperandRecycler.allocate( 11009 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11010 11011 bool IsDivergent = false; 11012 for (unsigned I = 0; I != Vals.size(); ++I) { 11013 Ops[I].setUser(Node); 11014 Ops[I].setInitial(Vals[I]); 11015 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11016 IsDivergent |= Ops[I].getNode()->isDivergent(); 11017 } 11018 Node->NumOperands = Vals.size(); 11019 Node->OperandList = Ops; 11020 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11021 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11022 Node->SDNodeBits.IsDivergent = IsDivergent; 11023 } 11024 checkForCycles(Node); 11025 } 11026 11027 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11028 SmallVectorImpl<SDValue> &Vals) { 11029 size_t Limit = SDNode::getMaxNumOperands(); 11030 while (Vals.size() > Limit) { 11031 unsigned SliceIdx = Vals.size() - Limit; 11032 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11033 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11034 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11035 Vals.emplace_back(NewTF); 11036 } 11037 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11038 } 11039 11040 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11041 EVT VT, SDNodeFlags Flags) { 11042 switch (Opcode) { 11043 default: 11044 return SDValue(); 11045 case ISD::ADD: 11046 case ISD::OR: 11047 case ISD::XOR: 11048 case ISD::UMAX: 11049 return getConstant(0, DL, VT); 11050 case ISD::MUL: 11051 return getConstant(1, DL, VT); 11052 case ISD::AND: 11053 case ISD::UMIN: 11054 return getAllOnesConstant(DL, VT); 11055 case ISD::SMAX: 11056 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11057 case ISD::SMIN: 11058 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11059 case ISD::FADD: 11060 return getConstantFP(-0.0, DL, VT); 11061 case ISD::FMUL: 11062 return getConstantFP(1.0, DL, VT); 11063 case ISD::FMINNUM: 11064 case ISD::FMAXNUM: { 11065 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11066 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11067 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11068 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11069 APFloat::getLargest(Semantics); 11070 if (Opcode == ISD::FMAXNUM) 11071 NeutralAF.changeSign(); 11072 11073 return getConstantFP(NeutralAF, DL, VT); 11074 } 11075 } 11076 } 11077 11078 #ifndef NDEBUG 11079 static void checkForCyclesHelper(const SDNode *N, 11080 SmallPtrSetImpl<const SDNode*> &Visited, 11081 SmallPtrSetImpl<const SDNode*> &Checked, 11082 const llvm::SelectionDAG *DAG) { 11083 // If this node has already been checked, don't check it again. 11084 if (Checked.count(N)) 11085 return; 11086 11087 // If a node has already been visited on this depth-first walk, reject it as 11088 // a cycle. 11089 if (!Visited.insert(N).second) { 11090 errs() << "Detected cycle in SelectionDAG\n"; 11091 dbgs() << "Offending node:\n"; 11092 N->dumprFull(DAG); dbgs() << "\n"; 11093 abort(); 11094 } 11095 11096 for (const SDValue &Op : N->op_values()) 11097 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11098 11099 Checked.insert(N); 11100 Visited.erase(N); 11101 } 11102 #endif 11103 11104 void llvm::checkForCycles(const llvm::SDNode *N, 11105 const llvm::SelectionDAG *DAG, 11106 bool force) { 11107 #ifndef NDEBUG 11108 bool check = force; 11109 #ifdef EXPENSIVE_CHECKS 11110 check = true; 11111 #endif // EXPENSIVE_CHECKS 11112 if (check) { 11113 assert(N && "Checking nonexistent SDNode"); 11114 SmallPtrSet<const SDNode*, 32> visited; 11115 SmallPtrSet<const SDNode*, 32> checked; 11116 checkForCyclesHelper(N, visited, checked, DAG); 11117 } 11118 #endif // !NDEBUG 11119 } 11120 11121 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11122 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11123 } 11124