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/FunctionLoweringInfo.h" 32 #include "llvm/CodeGen/ISDOpcodes.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineConstantPool.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/RuntimeLibcalls.h" 39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 40 #include "llvm/CodeGen/SelectionDAGNodes.h" 41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 42 #include "llvm/CodeGen/TargetFrameLowering.h" 43 #include "llvm/CodeGen/TargetLowering.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugInfoMetadata.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CodeGen.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/KnownBits.h" 64 #include "llvm/Support/MachineValueType.h" 65 #include "llvm/Support/ManagedStatic.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/Mutex.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include "llvm/Transforms/Utils/SizeOpts.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <cstdlib> 76 #include <limits> 77 #include <set> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 /// makeVTList - Return an instance of the SDVTList struct initialized with the 85 /// specified members. 86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 87 SDVTList Res = {VTs, NumVTs}; 88 return Res; 89 } 90 91 // Default null implementations of the callbacks. 92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 95 96 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 97 98 #define DEBUG_TYPE "selectiondag" 99 100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 101 cl::Hidden, cl::init(true), 102 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 103 104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 105 cl::desc("Number limit for gluing ld/st of memcpy."), 106 cl::Hidden, cl::init(0)); 107 108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 110 } 111 112 //===----------------------------------------------------------------------===// 113 // ConstantFPSDNode Class 114 //===----------------------------------------------------------------------===// 115 116 /// isExactlyValue - We don't rely on operator== working on double values, as 117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 118 /// As such, this method can be used to do an exact bit-for-bit comparison of 119 /// two floating point values. 120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 121 return getValueAPF().bitwiseIsEqual(V); 122 } 123 124 bool ConstantFPSDNode::isValueValidForType(EVT VT, 125 const APFloat& Val) { 126 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 127 128 // convert modifies in place, so make a copy. 129 APFloat Val2 = APFloat(Val); 130 bool losesInfo; 131 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 132 APFloat::rmNearestTiesToEven, 133 &losesInfo); 134 return !losesInfo; 135 } 136 137 //===----------------------------------------------------------------------===// 138 // ISD Namespace 139 //===----------------------------------------------------------------------===// 140 141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 142 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 143 unsigned EltSize = 144 N->getValueType(0).getVectorElementType().getSizeInBits(); 145 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 146 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 147 return true; 148 } 149 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 150 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 151 return true; 152 } 153 } 154 155 auto *BV = dyn_cast<BuildVectorSDNode>(N); 156 if (!BV) 157 return false; 158 159 APInt SplatUndef; 160 unsigned SplatBitSize; 161 bool HasUndefs; 162 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 163 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 164 EltSize) && 165 EltSize == SplatBitSize; 166 } 167 168 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 169 // specializations of the more general isConstantSplatVector()? 170 171 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 172 // Look through a bit convert. 173 while (N->getOpcode() == ISD::BITCAST) 174 N = N->getOperand(0).getNode(); 175 176 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 177 APInt SplatVal; 178 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue(); 179 } 180 181 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 182 183 unsigned i = 0, e = N->getNumOperands(); 184 185 // Skip over all of the undef values. 186 while (i != e && N->getOperand(i).isUndef()) 187 ++i; 188 189 // Do not accept an all-undef vector. 190 if (i == e) return false; 191 192 // Do not accept build_vectors that aren't all constants or which have non-~0 193 // elements. We have to be a bit careful here, as the type of the constant 194 // may not be the same as the type of the vector elements due to type 195 // legalization (the elements are promoted to a legal type for the target and 196 // a vector of a type may be legal when the base element type is not). 197 // We only want to check enough bits to cover the vector elements, because 198 // we care if the resultant vector is all ones, not whether the individual 199 // constants are. 200 SDValue NotZero = N->getOperand(i); 201 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 202 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 203 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 204 return false; 205 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 206 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 207 return false; 208 } else 209 return false; 210 211 // Okay, we have at least one ~0 value, check to see if the rest match or are 212 // undefs. Even with the above element type twiddling, this should be OK, as 213 // the same type legalization should have applied to all the elements. 214 for (++i; i != e; ++i) 215 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 216 return false; 217 return true; 218 } 219 220 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 221 // Look through a bit convert. 222 while (N->getOpcode() == ISD::BITCAST) 223 N = N->getOperand(0).getNode(); 224 225 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 226 APInt SplatVal; 227 return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue(); 228 } 229 230 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 231 232 bool IsAllUndef = true; 233 for (const SDValue &Op : N->op_values()) { 234 if (Op.isUndef()) 235 continue; 236 IsAllUndef = false; 237 // Do not accept build_vectors that aren't all constants or which have non-0 238 // elements. We have to be a bit careful here, as the type of the constant 239 // may not be the same as the type of the vector elements due to type 240 // legalization (the elements are promoted to a legal type for the target 241 // and a vector of a type may be legal when the base element type is not). 242 // We only want to check enough bits to cover the vector elements, because 243 // we care if the resultant vector is all zeros, not whether the individual 244 // constants are. 245 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 246 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 247 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 248 return false; 249 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 250 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 251 return false; 252 } else 253 return false; 254 } 255 256 // Do not accept an all-undef vector. 257 if (IsAllUndef) 258 return false; 259 return true; 260 } 261 262 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 263 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 264 } 265 266 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 267 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 268 } 269 270 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 271 if (N->getOpcode() != ISD::BUILD_VECTOR) 272 return false; 273 274 for (const SDValue &Op : N->op_values()) { 275 if (Op.isUndef()) 276 continue; 277 if (!isa<ConstantSDNode>(Op)) 278 return false; 279 } 280 return true; 281 } 282 283 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 284 if (N->getOpcode() != ISD::BUILD_VECTOR) 285 return false; 286 287 for (const SDValue &Op : N->op_values()) { 288 if (Op.isUndef()) 289 continue; 290 if (!isa<ConstantFPSDNode>(Op)) 291 return false; 292 } 293 return true; 294 } 295 296 bool ISD::allOperandsUndef(const SDNode *N) { 297 // Return false if the node has no operands. 298 // This is "logically inconsistent" with the definition of "all" but 299 // is probably the desired behavior. 300 if (N->getNumOperands() == 0) 301 return false; 302 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 303 } 304 305 bool ISD::matchUnaryPredicate(SDValue Op, 306 std::function<bool(ConstantSDNode *)> Match, 307 bool AllowUndefs) { 308 // FIXME: Add support for scalar UNDEF cases? 309 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 310 return Match(Cst); 311 312 // FIXME: Add support for vector UNDEF cases? 313 if (ISD::BUILD_VECTOR != Op.getOpcode() && 314 ISD::SPLAT_VECTOR != Op.getOpcode()) 315 return false; 316 317 EVT SVT = Op.getValueType().getScalarType(); 318 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 319 if (AllowUndefs && Op.getOperand(i).isUndef()) { 320 if (!Match(nullptr)) 321 return false; 322 continue; 323 } 324 325 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 326 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 327 return false; 328 } 329 return true; 330 } 331 332 bool ISD::matchBinaryPredicate( 333 SDValue LHS, SDValue RHS, 334 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 335 bool AllowUndefs, bool AllowTypeMismatch) { 336 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 337 return false; 338 339 // TODO: Add support for scalar UNDEF cases? 340 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 341 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 342 return Match(LHSCst, RHSCst); 343 344 // TODO: Add support for vector UNDEF cases? 345 if (LHS.getOpcode() != RHS.getOpcode() || 346 (LHS.getOpcode() != ISD::BUILD_VECTOR && 347 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 348 return false; 349 350 EVT SVT = LHS.getValueType().getScalarType(); 351 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 352 SDValue LHSOp = LHS.getOperand(i); 353 SDValue RHSOp = RHS.getOperand(i); 354 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 355 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 356 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 357 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 358 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 359 return false; 360 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 361 LHSOp.getValueType() != RHSOp.getValueType())) 362 return false; 363 if (!Match(LHSCst, RHSCst)) 364 return false; 365 } 366 return true; 367 } 368 369 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 370 switch (VecReduceOpcode) { 371 default: 372 llvm_unreachable("Expected VECREDUCE opcode"); 373 case ISD::VECREDUCE_FADD: 374 case ISD::VECREDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 return ISD::FMUL; 379 case ISD::VECREDUCE_ADD: 380 return ISD::ADD; 381 case ISD::VECREDUCE_MUL: 382 return ISD::MUL; 383 case ISD::VECREDUCE_AND: 384 return ISD::AND; 385 case ISD::VECREDUCE_OR: 386 return ISD::OR; 387 case ISD::VECREDUCE_XOR: 388 return ISD::XOR; 389 case ISD::VECREDUCE_SMAX: 390 return ISD::SMAX; 391 case ISD::VECREDUCE_SMIN: 392 return ISD::SMIN; 393 case ISD::VECREDUCE_UMAX: 394 return ISD::UMAX; 395 case ISD::VECREDUCE_UMIN: 396 return ISD::UMIN; 397 case ISD::VECREDUCE_FMAX: 398 return ISD::FMAXNUM; 399 case ISD::VECREDUCE_FMIN: 400 return ISD::FMINNUM; 401 } 402 } 403 404 bool ISD::isVPOpcode(unsigned Opcode) { 405 switch (Opcode) { 406 default: 407 return false; 408 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 409 case ISD::SDOPC: \ 410 return true; 411 #include "llvm/IR/VPIntrinsics.def" 412 } 413 } 414 415 /// The operand position of the vector mask. 416 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 417 switch (Opcode) { 418 default: 419 return None; 420 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 421 case ISD::SDOPC: \ 422 return MASKPOS; 423 #include "llvm/IR/VPIntrinsics.def" 424 } 425 } 426 427 /// The operand position of the explicit vector length parameter. 428 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 return None; 432 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 433 case ISD::SDOPC: \ 434 return EVLPOS; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 } 438 439 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 440 switch (ExtType) { 441 case ISD::EXTLOAD: 442 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 443 case ISD::SEXTLOAD: 444 return ISD::SIGN_EXTEND; 445 case ISD::ZEXTLOAD: 446 return ISD::ZERO_EXTEND; 447 default: 448 break; 449 } 450 451 llvm_unreachable("Invalid LoadExtType"); 452 } 453 454 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 455 // To perform this operation, we just need to swap the L and G bits of the 456 // operation. 457 unsigned OldL = (Operation >> 2) & 1; 458 unsigned OldG = (Operation >> 1) & 1; 459 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 460 (OldL << 1) | // New G bit 461 (OldG << 2)); // New L bit. 462 } 463 464 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 465 unsigned Operation = Op; 466 if (isIntegerLike) 467 Operation ^= 7; // Flip L, G, E bits, but not U. 468 else 469 Operation ^= 15; // Flip all of the condition bits. 470 471 if (Operation > ISD::SETTRUE2) 472 Operation &= ~8; // Don't let N and U bits get set. 473 474 return ISD::CondCode(Operation); 475 } 476 477 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 478 return getSetCCInverseImpl(Op, Type.isInteger()); 479 } 480 481 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 482 bool isIntegerLike) { 483 return getSetCCInverseImpl(Op, isIntegerLike); 484 } 485 486 /// For an integer comparison, return 1 if the comparison is a signed operation 487 /// and 2 if the result is an unsigned comparison. Return zero if the operation 488 /// does not depend on the sign of the input (setne and seteq). 489 static int isSignedOp(ISD::CondCode Opcode) { 490 switch (Opcode) { 491 default: llvm_unreachable("Illegal integer setcc operation!"); 492 case ISD::SETEQ: 493 case ISD::SETNE: return 0; 494 case ISD::SETLT: 495 case ISD::SETLE: 496 case ISD::SETGT: 497 case ISD::SETGE: return 1; 498 case ISD::SETULT: 499 case ISD::SETULE: 500 case ISD::SETUGT: 501 case ISD::SETUGE: return 2; 502 } 503 } 504 505 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 506 EVT Type) { 507 bool IsInteger = Type.isInteger(); 508 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 509 // Cannot fold a signed integer setcc with an unsigned integer setcc. 510 return ISD::SETCC_INVALID; 511 512 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 513 514 // If the N and U bits get set, then the resultant comparison DOES suddenly 515 // care about orderedness, and it is true when ordered. 516 if (Op > ISD::SETTRUE2) 517 Op &= ~16; // Clear the U bit if the N bit is set. 518 519 // Canonicalize illegal integer setcc's. 520 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 521 Op = ISD::SETNE; 522 523 return ISD::CondCode(Op); 524 } 525 526 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 527 EVT Type) { 528 bool IsInteger = Type.isInteger(); 529 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 530 // Cannot fold a signed setcc with an unsigned setcc. 531 return ISD::SETCC_INVALID; 532 533 // Combine all of the condition bits. 534 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 535 536 // Canonicalize illegal integer setcc's. 537 if (IsInteger) { 538 switch (Result) { 539 default: break; 540 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 541 case ISD::SETOEQ: // SETEQ & SETU[LG]E 542 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 543 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 544 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 545 } 546 } 547 548 return Result; 549 } 550 551 //===----------------------------------------------------------------------===// 552 // SDNode Profile Support 553 //===----------------------------------------------------------------------===// 554 555 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 556 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 557 ID.AddInteger(OpC); 558 } 559 560 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 561 /// solely with their pointer. 562 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 563 ID.AddPointer(VTList.VTs); 564 } 565 566 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 567 static void AddNodeIDOperands(FoldingSetNodeID &ID, 568 ArrayRef<SDValue> Ops) { 569 for (auto& Op : Ops) { 570 ID.AddPointer(Op.getNode()); 571 ID.AddInteger(Op.getResNo()); 572 } 573 } 574 575 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 576 static void AddNodeIDOperands(FoldingSetNodeID &ID, 577 ArrayRef<SDUse> Ops) { 578 for (auto& Op : Ops) { 579 ID.AddPointer(Op.getNode()); 580 ID.AddInteger(Op.getResNo()); 581 } 582 } 583 584 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 585 SDVTList VTList, ArrayRef<SDValue> OpList) { 586 AddNodeIDOpcode(ID, OpC); 587 AddNodeIDValueTypes(ID, VTList); 588 AddNodeIDOperands(ID, OpList); 589 } 590 591 /// If this is an SDNode with special info, add this info to the NodeID data. 592 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 593 switch (N->getOpcode()) { 594 case ISD::TargetExternalSymbol: 595 case ISD::ExternalSymbol: 596 case ISD::MCSymbol: 597 llvm_unreachable("Should only be used on nodes with operands"); 598 default: break; // Normal nodes don't need extra info. 599 case ISD::TargetConstant: 600 case ISD::Constant: { 601 const ConstantSDNode *C = cast<ConstantSDNode>(N); 602 ID.AddPointer(C->getConstantIntValue()); 603 ID.AddBoolean(C->isOpaque()); 604 break; 605 } 606 case ISD::TargetConstantFP: 607 case ISD::ConstantFP: 608 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 609 break; 610 case ISD::TargetGlobalAddress: 611 case ISD::GlobalAddress: 612 case ISD::TargetGlobalTLSAddress: 613 case ISD::GlobalTLSAddress: { 614 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 615 ID.AddPointer(GA->getGlobal()); 616 ID.AddInteger(GA->getOffset()); 617 ID.AddInteger(GA->getTargetFlags()); 618 break; 619 } 620 case ISD::BasicBlock: 621 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 622 break; 623 case ISD::Register: 624 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 625 break; 626 case ISD::RegisterMask: 627 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 628 break; 629 case ISD::SRCVALUE: 630 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 631 break; 632 case ISD::FrameIndex: 633 case ISD::TargetFrameIndex: 634 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 635 break; 636 case ISD::LIFETIME_START: 637 case ISD::LIFETIME_END: 638 if (cast<LifetimeSDNode>(N)->hasOffset()) { 639 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 640 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 641 } 642 break; 643 case ISD::PSEUDO_PROBE: 644 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 645 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 646 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 647 break; 648 case ISD::JumpTable: 649 case ISD::TargetJumpTable: 650 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 651 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 652 break; 653 case ISD::ConstantPool: 654 case ISD::TargetConstantPool: { 655 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 656 ID.AddInteger(CP->getAlign().value()); 657 ID.AddInteger(CP->getOffset()); 658 if (CP->isMachineConstantPoolEntry()) 659 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 660 else 661 ID.AddPointer(CP->getConstVal()); 662 ID.AddInteger(CP->getTargetFlags()); 663 break; 664 } 665 case ISD::TargetIndex: { 666 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 667 ID.AddInteger(TI->getIndex()); 668 ID.AddInteger(TI->getOffset()); 669 ID.AddInteger(TI->getTargetFlags()); 670 break; 671 } 672 case ISD::LOAD: { 673 const LoadSDNode *LD = cast<LoadSDNode>(N); 674 ID.AddInteger(LD->getMemoryVT().getRawBits()); 675 ID.AddInteger(LD->getRawSubclassData()); 676 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 677 break; 678 } 679 case ISD::STORE: { 680 const StoreSDNode *ST = cast<StoreSDNode>(N); 681 ID.AddInteger(ST->getMemoryVT().getRawBits()); 682 ID.AddInteger(ST->getRawSubclassData()); 683 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 684 break; 685 } 686 case ISD::MLOAD: { 687 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 688 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 689 ID.AddInteger(MLD->getRawSubclassData()); 690 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 691 break; 692 } 693 case ISD::MSTORE: { 694 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 695 ID.AddInteger(MST->getMemoryVT().getRawBits()); 696 ID.AddInteger(MST->getRawSubclassData()); 697 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 698 break; 699 } 700 case ISD::MGATHER: { 701 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 702 ID.AddInteger(MG->getMemoryVT().getRawBits()); 703 ID.AddInteger(MG->getRawSubclassData()); 704 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 705 break; 706 } 707 case ISD::MSCATTER: { 708 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 709 ID.AddInteger(MS->getMemoryVT().getRawBits()); 710 ID.AddInteger(MS->getRawSubclassData()); 711 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 712 break; 713 } 714 case ISD::ATOMIC_CMP_SWAP: 715 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 716 case ISD::ATOMIC_SWAP: 717 case ISD::ATOMIC_LOAD_ADD: 718 case ISD::ATOMIC_LOAD_SUB: 719 case ISD::ATOMIC_LOAD_AND: 720 case ISD::ATOMIC_LOAD_CLR: 721 case ISD::ATOMIC_LOAD_OR: 722 case ISD::ATOMIC_LOAD_XOR: 723 case ISD::ATOMIC_LOAD_NAND: 724 case ISD::ATOMIC_LOAD_MIN: 725 case ISD::ATOMIC_LOAD_MAX: 726 case ISD::ATOMIC_LOAD_UMIN: 727 case ISD::ATOMIC_LOAD_UMAX: 728 case ISD::ATOMIC_LOAD: 729 case ISD::ATOMIC_STORE: { 730 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 731 ID.AddInteger(AT->getMemoryVT().getRawBits()); 732 ID.AddInteger(AT->getRawSubclassData()); 733 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 734 break; 735 } 736 case ISD::PREFETCH: { 737 const MemSDNode *PF = cast<MemSDNode>(N); 738 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 739 break; 740 } 741 case ISD::VECTOR_SHUFFLE: { 742 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 743 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 744 i != e; ++i) 745 ID.AddInteger(SVN->getMaskElt(i)); 746 break; 747 } 748 case ISD::TargetBlockAddress: 749 case ISD::BlockAddress: { 750 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 751 ID.AddPointer(BA->getBlockAddress()); 752 ID.AddInteger(BA->getOffset()); 753 ID.AddInteger(BA->getTargetFlags()); 754 break; 755 } 756 } // end switch (N->getOpcode()) 757 758 // Target specific memory nodes could also have address spaces to check. 759 if (N->isTargetMemoryOpcode()) 760 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 761 } 762 763 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 764 /// data. 765 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 766 AddNodeIDOpcode(ID, N->getOpcode()); 767 // Add the return value info. 768 AddNodeIDValueTypes(ID, N->getVTList()); 769 // Add the operand info. 770 AddNodeIDOperands(ID, N->ops()); 771 772 // Handle SDNode leafs with special info. 773 AddNodeIDCustom(ID, N); 774 } 775 776 //===----------------------------------------------------------------------===// 777 // SelectionDAG Class 778 //===----------------------------------------------------------------------===// 779 780 /// doNotCSE - Return true if CSE should not be performed for this node. 781 static bool doNotCSE(SDNode *N) { 782 if (N->getValueType(0) == MVT::Glue) 783 return true; // Never CSE anything that produces a flag. 784 785 switch (N->getOpcode()) { 786 default: break; 787 case ISD::HANDLENODE: 788 case ISD::EH_LABEL: 789 return true; // Never CSE these nodes. 790 } 791 792 // Check that remaining values produced are not flags. 793 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 794 if (N->getValueType(i) == MVT::Glue) 795 return true; // Never CSE anything that produces a flag. 796 797 return false; 798 } 799 800 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 801 /// SelectionDAG. 802 void SelectionDAG::RemoveDeadNodes() { 803 // Create a dummy node (which is not added to allnodes), that adds a reference 804 // to the root node, preventing it from being deleted. 805 HandleSDNode Dummy(getRoot()); 806 807 SmallVector<SDNode*, 128> DeadNodes; 808 809 // Add all obviously-dead nodes to the DeadNodes worklist. 810 for (SDNode &Node : allnodes()) 811 if (Node.use_empty()) 812 DeadNodes.push_back(&Node); 813 814 RemoveDeadNodes(DeadNodes); 815 816 // If the root changed (e.g. it was a dead load, update the root). 817 setRoot(Dummy.getValue()); 818 } 819 820 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 821 /// given list, and any nodes that become unreachable as a result. 822 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 823 824 // Process the worklist, deleting the nodes and adding their uses to the 825 // worklist. 826 while (!DeadNodes.empty()) { 827 SDNode *N = DeadNodes.pop_back_val(); 828 // Skip to next node if we've already managed to delete the node. This could 829 // happen if replacing a node causes a node previously added to the node to 830 // be deleted. 831 if (N->getOpcode() == ISD::DELETED_NODE) 832 continue; 833 834 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 835 DUL->NodeDeleted(N, nullptr); 836 837 // Take the node out of the appropriate CSE map. 838 RemoveNodeFromCSEMaps(N); 839 840 // Next, brutally remove the operand list. This is safe to do, as there are 841 // no cycles in the graph. 842 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 843 SDUse &Use = *I++; 844 SDNode *Operand = Use.getNode(); 845 Use.set(SDValue()); 846 847 // Now that we removed this operand, see if there are no uses of it left. 848 if (Operand->use_empty()) 849 DeadNodes.push_back(Operand); 850 } 851 852 DeallocateNode(N); 853 } 854 } 855 856 void SelectionDAG::RemoveDeadNode(SDNode *N){ 857 SmallVector<SDNode*, 16> DeadNodes(1, N); 858 859 // Create a dummy node that adds a reference to the root node, preventing 860 // it from being deleted. (This matters if the root is an operand of the 861 // dead node.) 862 HandleSDNode Dummy(getRoot()); 863 864 RemoveDeadNodes(DeadNodes); 865 } 866 867 void SelectionDAG::DeleteNode(SDNode *N) { 868 // First take this out of the appropriate CSE map. 869 RemoveNodeFromCSEMaps(N); 870 871 // Finally, remove uses due to operands of this node, remove from the 872 // AllNodes list, and delete the node. 873 DeleteNodeNotInCSEMaps(N); 874 } 875 876 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 877 assert(N->getIterator() != AllNodes.begin() && 878 "Cannot delete the entry node!"); 879 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 880 881 // Drop all of the operands and decrement used node's use counts. 882 N->DropOperands(); 883 884 DeallocateNode(N); 885 } 886 887 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 888 assert(!(V->isVariadic() && isParameter)); 889 if (isParameter) 890 ByvalParmDbgValues.push_back(V); 891 else 892 DbgValues.push_back(V); 893 for (const SDNode *Node : V->getSDNodes()) 894 if (Node) 895 DbgValMap[Node].push_back(V); 896 } 897 898 void SDDbgInfo::erase(const SDNode *Node) { 899 DbgValMapType::iterator I = DbgValMap.find(Node); 900 if (I == DbgValMap.end()) 901 return; 902 for (auto &Val: I->second) 903 Val->setIsInvalidated(); 904 DbgValMap.erase(I); 905 } 906 907 void SelectionDAG::DeallocateNode(SDNode *N) { 908 // If we have operands, deallocate them. 909 removeOperands(N); 910 911 NodeAllocator.Deallocate(AllNodes.remove(N)); 912 913 // Set the opcode to DELETED_NODE to help catch bugs when node 914 // memory is reallocated. 915 // FIXME: There are places in SDag that have grown a dependency on the opcode 916 // value in the released node. 917 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 918 N->NodeType = ISD::DELETED_NODE; 919 920 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 921 // them and forget about that node. 922 DbgInfo->erase(N); 923 } 924 925 #ifndef NDEBUG 926 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 927 static void VerifySDNode(SDNode *N) { 928 switch (N->getOpcode()) { 929 default: 930 break; 931 case ISD::BUILD_PAIR: { 932 EVT VT = N->getValueType(0); 933 assert(N->getNumValues() == 1 && "Too many results!"); 934 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 935 "Wrong return type!"); 936 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 937 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 938 "Mismatched operand types!"); 939 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 940 "Wrong operand type!"); 941 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 942 "Wrong return type size"); 943 break; 944 } 945 case ISD::BUILD_VECTOR: { 946 assert(N->getNumValues() == 1 && "Too many results!"); 947 assert(N->getValueType(0).isVector() && "Wrong return type!"); 948 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 949 "Wrong number of operands!"); 950 EVT EltVT = N->getValueType(0).getVectorElementType(); 951 for (const SDUse &Op : N->ops()) { 952 assert((Op.getValueType() == EltVT || 953 (EltVT.isInteger() && Op.getValueType().isInteger() && 954 EltVT.bitsLE(Op.getValueType()))) && 955 "Wrong operand type!"); 956 assert(Op.getValueType() == N->getOperand(0).getValueType() && 957 "Operands must all have the same type"); 958 } 959 break; 960 } 961 } 962 } 963 #endif // NDEBUG 964 965 /// Insert a newly allocated node into the DAG. 966 /// 967 /// Handles insertion into the all nodes list and CSE map, as well as 968 /// verification and other common operations when a new node is allocated. 969 void SelectionDAG::InsertNode(SDNode *N) { 970 AllNodes.push_back(N); 971 #ifndef NDEBUG 972 N->PersistentId = NextPersistentId++; 973 VerifySDNode(N); 974 #endif 975 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 976 DUL->NodeInserted(N); 977 } 978 979 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 980 /// correspond to it. This is useful when we're about to delete or repurpose 981 /// the node. We don't want future request for structurally identical nodes 982 /// to return N anymore. 983 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 984 bool Erased = false; 985 switch (N->getOpcode()) { 986 case ISD::HANDLENODE: return false; // noop. 987 case ISD::CONDCODE: 988 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 989 "Cond code doesn't exist!"); 990 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 991 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 992 break; 993 case ISD::ExternalSymbol: 994 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 995 break; 996 case ISD::TargetExternalSymbol: { 997 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 998 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 999 ESN->getSymbol(), ESN->getTargetFlags())); 1000 break; 1001 } 1002 case ISD::MCSymbol: { 1003 auto *MCSN = cast<MCSymbolSDNode>(N); 1004 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1005 break; 1006 } 1007 case ISD::VALUETYPE: { 1008 EVT VT = cast<VTSDNode>(N)->getVT(); 1009 if (VT.isExtended()) { 1010 Erased = ExtendedValueTypeNodes.erase(VT); 1011 } else { 1012 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1013 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1014 } 1015 break; 1016 } 1017 default: 1018 // Remove it from the CSE Map. 1019 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1020 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1021 Erased = CSEMap.RemoveNode(N); 1022 break; 1023 } 1024 #ifndef NDEBUG 1025 // Verify that the node was actually in one of the CSE maps, unless it has a 1026 // flag result (which cannot be CSE'd) or is one of the special cases that are 1027 // not subject to CSE. 1028 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1029 !N->isMachineOpcode() && !doNotCSE(N)) { 1030 N->dump(this); 1031 dbgs() << "\n"; 1032 llvm_unreachable("Node is not in map!"); 1033 } 1034 #endif 1035 return Erased; 1036 } 1037 1038 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1039 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1040 /// node already exists, in which case transfer all its users to the existing 1041 /// node. This transfer can potentially trigger recursive merging. 1042 void 1043 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1044 // For node types that aren't CSE'd, just act as if no identical node 1045 // already exists. 1046 if (!doNotCSE(N)) { 1047 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1048 if (Existing != N) { 1049 // If there was already an existing matching node, use ReplaceAllUsesWith 1050 // to replace the dead one with the existing one. This can cause 1051 // recursive merging of other unrelated nodes down the line. 1052 ReplaceAllUsesWith(N, Existing); 1053 1054 // N is now dead. Inform the listeners and delete it. 1055 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1056 DUL->NodeDeleted(N, Existing); 1057 DeleteNodeNotInCSEMaps(N); 1058 return; 1059 } 1060 } 1061 1062 // If the node doesn't already exist, we updated it. Inform listeners. 1063 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1064 DUL->NodeUpdated(N); 1065 } 1066 1067 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1068 /// were replaced with those specified. If this node is never memoized, 1069 /// return null, otherwise return a pointer to the slot it would take. If a 1070 /// node already exists with these operands, the slot will be non-null. 1071 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1072 void *&InsertPos) { 1073 if (doNotCSE(N)) 1074 return nullptr; 1075 1076 SDValue Ops[] = { Op }; 1077 FoldingSetNodeID ID; 1078 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1079 AddNodeIDCustom(ID, N); 1080 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1081 if (Node) 1082 Node->intersectFlagsWith(N->getFlags()); 1083 return Node; 1084 } 1085 1086 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1087 /// were replaced with those specified. If this node is never memoized, 1088 /// return null, otherwise return a pointer to the slot it would take. If a 1089 /// node already exists with these operands, the slot will be non-null. 1090 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1091 SDValue Op1, SDValue Op2, 1092 void *&InsertPos) { 1093 if (doNotCSE(N)) 1094 return nullptr; 1095 1096 SDValue Ops[] = { Op1, Op2 }; 1097 FoldingSetNodeID ID; 1098 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1099 AddNodeIDCustom(ID, N); 1100 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1101 if (Node) 1102 Node->intersectFlagsWith(N->getFlags()); 1103 return Node; 1104 } 1105 1106 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1107 /// were replaced with those specified. If this node is never memoized, 1108 /// return null, otherwise return a pointer to the slot it would take. If a 1109 /// node already exists with these operands, the slot will be non-null. 1110 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1111 void *&InsertPos) { 1112 if (doNotCSE(N)) 1113 return nullptr; 1114 1115 FoldingSetNodeID ID; 1116 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1117 AddNodeIDCustom(ID, N); 1118 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1119 if (Node) 1120 Node->intersectFlagsWith(N->getFlags()); 1121 return Node; 1122 } 1123 1124 Align SelectionDAG::getEVTAlign(EVT VT) const { 1125 Type *Ty = VT == MVT::iPTR ? 1126 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1127 VT.getTypeForEVT(*getContext()); 1128 1129 return getDataLayout().getABITypeAlign(Ty); 1130 } 1131 1132 // EntryNode could meaningfully have debug info if we can find it... 1133 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1134 : TM(tm), OptLevel(OL), 1135 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1136 Root(getEntryNode()) { 1137 InsertNode(&EntryNode); 1138 DbgInfo = new SDDbgInfo(); 1139 } 1140 1141 void SelectionDAG::init(MachineFunction &NewMF, 1142 OptimizationRemarkEmitter &NewORE, 1143 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1144 LegacyDivergenceAnalysis * Divergence, 1145 ProfileSummaryInfo *PSIin, 1146 BlockFrequencyInfo *BFIin) { 1147 MF = &NewMF; 1148 SDAGISelPass = PassPtr; 1149 ORE = &NewORE; 1150 TLI = getSubtarget().getTargetLowering(); 1151 TSI = getSubtarget().getSelectionDAGInfo(); 1152 LibInfo = LibraryInfo; 1153 Context = &MF->getFunction().getContext(); 1154 DA = Divergence; 1155 PSI = PSIin; 1156 BFI = BFIin; 1157 } 1158 1159 SelectionDAG::~SelectionDAG() { 1160 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1161 allnodes_clear(); 1162 OperandRecycler.clear(OperandAllocator); 1163 delete DbgInfo; 1164 } 1165 1166 bool SelectionDAG::shouldOptForSize() const { 1167 return MF->getFunction().hasOptSize() || 1168 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1169 } 1170 1171 void SelectionDAG::allnodes_clear() { 1172 assert(&*AllNodes.begin() == &EntryNode); 1173 AllNodes.remove(AllNodes.begin()); 1174 while (!AllNodes.empty()) 1175 DeallocateNode(&AllNodes.front()); 1176 #ifndef NDEBUG 1177 NextPersistentId = 0; 1178 #endif 1179 } 1180 1181 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1182 void *&InsertPos) { 1183 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1184 if (N) { 1185 switch (N->getOpcode()) { 1186 default: break; 1187 case ISD::Constant: 1188 case ISD::ConstantFP: 1189 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1190 "debug location. Use another overload."); 1191 } 1192 } 1193 return N; 1194 } 1195 1196 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1197 const SDLoc &DL, void *&InsertPos) { 1198 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1199 if (N) { 1200 switch (N->getOpcode()) { 1201 case ISD::Constant: 1202 case ISD::ConstantFP: 1203 // Erase debug location from the node if the node is used at several 1204 // different places. Do not propagate one location to all uses as it 1205 // will cause a worse single stepping debugging experience. 1206 if (N->getDebugLoc() != DL.getDebugLoc()) 1207 N->setDebugLoc(DebugLoc()); 1208 break; 1209 default: 1210 // When the node's point of use is located earlier in the instruction 1211 // sequence than its prior point of use, update its debug info to the 1212 // earlier location. 1213 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1214 N->setDebugLoc(DL.getDebugLoc()); 1215 break; 1216 } 1217 } 1218 return N; 1219 } 1220 1221 void SelectionDAG::clear() { 1222 allnodes_clear(); 1223 OperandRecycler.clear(OperandAllocator); 1224 OperandAllocator.Reset(); 1225 CSEMap.clear(); 1226 1227 ExtendedValueTypeNodes.clear(); 1228 ExternalSymbols.clear(); 1229 TargetExternalSymbols.clear(); 1230 MCSymbols.clear(); 1231 SDCallSiteDbgInfo.clear(); 1232 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1233 static_cast<CondCodeSDNode*>(nullptr)); 1234 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1235 static_cast<SDNode*>(nullptr)); 1236 1237 EntryNode.UseList = nullptr; 1238 InsertNode(&EntryNode); 1239 Root = getEntryNode(); 1240 DbgInfo->clear(); 1241 } 1242 1243 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1244 return VT.bitsGT(Op.getValueType()) 1245 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1246 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1247 } 1248 1249 std::pair<SDValue, SDValue> 1250 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1251 const SDLoc &DL, EVT VT) { 1252 assert(!VT.bitsEq(Op.getValueType()) && 1253 "Strict no-op FP extend/round not allowed."); 1254 SDValue Res = 1255 VT.bitsGT(Op.getValueType()) 1256 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1257 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1258 {Chain, Op, getIntPtrConstant(0, DL)}); 1259 1260 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1261 } 1262 1263 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1264 return VT.bitsGT(Op.getValueType()) ? 1265 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1266 getNode(ISD::TRUNCATE, DL, VT, Op); 1267 } 1268 1269 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1270 return VT.bitsGT(Op.getValueType()) ? 1271 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1272 getNode(ISD::TRUNCATE, DL, VT, Op); 1273 } 1274 1275 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1276 return VT.bitsGT(Op.getValueType()) ? 1277 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1278 getNode(ISD::TRUNCATE, DL, VT, Op); 1279 } 1280 1281 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1282 EVT OpVT) { 1283 if (VT.bitsLE(Op.getValueType())) 1284 return getNode(ISD::TRUNCATE, SL, VT, Op); 1285 1286 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1287 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1288 } 1289 1290 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1291 EVT OpVT = Op.getValueType(); 1292 assert(VT.isInteger() && OpVT.isInteger() && 1293 "Cannot getZeroExtendInReg FP types"); 1294 assert(VT.isVector() == OpVT.isVector() && 1295 "getZeroExtendInReg type should be vector iff the operand " 1296 "type is vector!"); 1297 assert((!VT.isVector() || 1298 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1299 "Vector element counts must match in getZeroExtendInReg"); 1300 assert(VT.bitsLE(OpVT) && "Not extending!"); 1301 if (OpVT == VT) 1302 return Op; 1303 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1304 VT.getScalarSizeInBits()); 1305 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1306 } 1307 1308 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1309 // Only unsigned pointer semantics are supported right now. In the future this 1310 // might delegate to TLI to check pointer signedness. 1311 return getZExtOrTrunc(Op, DL, VT); 1312 } 1313 1314 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1315 // Only unsigned pointer semantics are supported right now. In the future this 1316 // might delegate to TLI to check pointer signedness. 1317 return getZeroExtendInReg(Op, DL, VT); 1318 } 1319 1320 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1321 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1322 EVT EltVT = VT.getScalarType(); 1323 SDValue NegOne = 1324 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1325 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1326 } 1327 1328 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1329 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1330 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1331 } 1332 1333 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1334 EVT OpVT) { 1335 if (!V) 1336 return getConstant(0, DL, VT); 1337 1338 switch (TLI->getBooleanContents(OpVT)) { 1339 case TargetLowering::ZeroOrOneBooleanContent: 1340 case TargetLowering::UndefinedBooleanContent: 1341 return getConstant(1, DL, VT); 1342 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1343 return getAllOnesConstant(DL, VT); 1344 } 1345 llvm_unreachable("Unexpected boolean content enum!"); 1346 } 1347 1348 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1349 bool isT, bool isO) { 1350 EVT EltVT = VT.getScalarType(); 1351 assert((EltVT.getSizeInBits() >= 64 || 1352 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1353 "getConstant with a uint64_t value that doesn't fit in the type!"); 1354 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1355 } 1356 1357 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1358 bool isT, bool isO) { 1359 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1360 } 1361 1362 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1363 EVT VT, bool isT, bool isO) { 1364 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1365 1366 EVT EltVT = VT.getScalarType(); 1367 const ConstantInt *Elt = &Val; 1368 1369 // In some cases the vector type is legal but the element type is illegal and 1370 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1371 // inserted value (the type does not need to match the vector element type). 1372 // Any extra bits introduced will be truncated away. 1373 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1374 TargetLowering::TypePromoteInteger) { 1375 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1376 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1377 Elt = ConstantInt::get(*getContext(), NewVal); 1378 } 1379 // In other cases the element type is illegal and needs to be expanded, for 1380 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1381 // the value into n parts and use a vector type with n-times the elements. 1382 // Then bitcast to the type requested. 1383 // Legalizing constants too early makes the DAGCombiner's job harder so we 1384 // only legalize if the DAG tells us we must produce legal types. 1385 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1386 TLI->getTypeAction(*getContext(), EltVT) == 1387 TargetLowering::TypeExpandInteger) { 1388 const APInt &NewVal = Elt->getValue(); 1389 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1390 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1391 1392 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1393 if (VT.isScalableVector()) { 1394 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1395 "Can only handle an even split!"); 1396 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1397 1398 SmallVector<SDValue, 2> ScalarParts; 1399 for (unsigned i = 0; i != Parts; ++i) 1400 ScalarParts.push_back(getConstant( 1401 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1402 ViaEltVT, isT, isO)); 1403 1404 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1405 } 1406 1407 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1408 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1409 1410 // Check the temporary vector is the correct size. If this fails then 1411 // getTypeToTransformTo() probably returned a type whose size (in bits) 1412 // isn't a power-of-2 factor of the requested type size. 1413 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1414 1415 SmallVector<SDValue, 2> EltParts; 1416 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1417 EltParts.push_back(getConstant( 1418 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1419 ViaEltVT, isT, isO)); 1420 1421 // EltParts is currently in little endian order. If we actually want 1422 // big-endian order then reverse it now. 1423 if (getDataLayout().isBigEndian()) 1424 std::reverse(EltParts.begin(), EltParts.end()); 1425 1426 // The elements must be reversed when the element order is different 1427 // to the endianness of the elements (because the BITCAST is itself a 1428 // vector shuffle in this situation). However, we do not need any code to 1429 // perform this reversal because getConstant() is producing a vector 1430 // splat. 1431 // This situation occurs in MIPS MSA. 1432 1433 SmallVector<SDValue, 8> Ops; 1434 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1435 llvm::append_range(Ops, EltParts); 1436 1437 SDValue V = 1438 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1439 return V; 1440 } 1441 1442 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1443 "APInt size does not match type size!"); 1444 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1445 FoldingSetNodeID ID; 1446 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1447 ID.AddPointer(Elt); 1448 ID.AddBoolean(isO); 1449 void *IP = nullptr; 1450 SDNode *N = nullptr; 1451 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1452 if (!VT.isVector()) 1453 return SDValue(N, 0); 1454 1455 if (!N) { 1456 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1457 CSEMap.InsertNode(N, IP); 1458 InsertNode(N); 1459 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1460 } 1461 1462 SDValue Result(N, 0); 1463 if (VT.isScalableVector()) 1464 Result = getSplatVector(VT, DL, Result); 1465 else if (VT.isVector()) 1466 Result = getSplatBuildVector(VT, DL, Result); 1467 1468 return Result; 1469 } 1470 1471 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1472 bool isTarget) { 1473 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1474 } 1475 1476 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1477 const SDLoc &DL, bool LegalTypes) { 1478 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1479 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1480 return getConstant(Val, DL, ShiftVT); 1481 } 1482 1483 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1484 bool isTarget) { 1485 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1486 } 1487 1488 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1489 bool isTarget) { 1490 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1491 } 1492 1493 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1494 EVT VT, bool isTarget) { 1495 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1496 1497 EVT EltVT = VT.getScalarType(); 1498 1499 // Do the map lookup using the actual bit pattern for the floating point 1500 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1501 // we don't have issues with SNANs. 1502 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1503 FoldingSetNodeID ID; 1504 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1505 ID.AddPointer(&V); 1506 void *IP = nullptr; 1507 SDNode *N = nullptr; 1508 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1509 if (!VT.isVector()) 1510 return SDValue(N, 0); 1511 1512 if (!N) { 1513 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1514 CSEMap.InsertNode(N, IP); 1515 InsertNode(N); 1516 } 1517 1518 SDValue Result(N, 0); 1519 if (VT.isScalableVector()) 1520 Result = getSplatVector(VT, DL, Result); 1521 else if (VT.isVector()) 1522 Result = getSplatBuildVector(VT, DL, Result); 1523 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1524 return Result; 1525 } 1526 1527 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1528 bool isTarget) { 1529 EVT EltVT = VT.getScalarType(); 1530 if (EltVT == MVT::f32) 1531 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1532 if (EltVT == MVT::f64) 1533 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1534 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1535 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1536 bool Ignored; 1537 APFloat APF = APFloat(Val); 1538 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1539 &Ignored); 1540 return getConstantFP(APF, DL, VT, isTarget); 1541 } 1542 llvm_unreachable("Unsupported type in getConstantFP"); 1543 } 1544 1545 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1546 EVT VT, int64_t Offset, bool isTargetGA, 1547 unsigned TargetFlags) { 1548 assert((TargetFlags == 0 || isTargetGA) && 1549 "Cannot set target flags on target-independent globals"); 1550 1551 // Truncate (with sign-extension) the offset value to the pointer size. 1552 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1553 if (BitWidth < 64) 1554 Offset = SignExtend64(Offset, BitWidth); 1555 1556 unsigned Opc; 1557 if (GV->isThreadLocal()) 1558 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1559 else 1560 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1561 1562 FoldingSetNodeID ID; 1563 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1564 ID.AddPointer(GV); 1565 ID.AddInteger(Offset); 1566 ID.AddInteger(TargetFlags); 1567 void *IP = nullptr; 1568 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1569 return SDValue(E, 0); 1570 1571 auto *N = newSDNode<GlobalAddressSDNode>( 1572 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1573 CSEMap.InsertNode(N, IP); 1574 InsertNode(N); 1575 return SDValue(N, 0); 1576 } 1577 1578 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1579 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1580 FoldingSetNodeID ID; 1581 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1582 ID.AddInteger(FI); 1583 void *IP = nullptr; 1584 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1585 return SDValue(E, 0); 1586 1587 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1588 CSEMap.InsertNode(N, IP); 1589 InsertNode(N); 1590 return SDValue(N, 0); 1591 } 1592 1593 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1594 unsigned TargetFlags) { 1595 assert((TargetFlags == 0 || isTarget) && 1596 "Cannot set target flags on target-independent jump tables"); 1597 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1598 FoldingSetNodeID ID; 1599 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1600 ID.AddInteger(JTI); 1601 ID.AddInteger(TargetFlags); 1602 void *IP = nullptr; 1603 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1604 return SDValue(E, 0); 1605 1606 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1607 CSEMap.InsertNode(N, IP); 1608 InsertNode(N); 1609 return SDValue(N, 0); 1610 } 1611 1612 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1613 MaybeAlign Alignment, int Offset, 1614 bool isTarget, unsigned TargetFlags) { 1615 assert((TargetFlags == 0 || isTarget) && 1616 "Cannot set target flags on target-independent globals"); 1617 if (!Alignment) 1618 Alignment = shouldOptForSize() 1619 ? getDataLayout().getABITypeAlign(C->getType()) 1620 : getDataLayout().getPrefTypeAlign(C->getType()); 1621 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1622 FoldingSetNodeID ID; 1623 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1624 ID.AddInteger(Alignment->value()); 1625 ID.AddInteger(Offset); 1626 ID.AddPointer(C); 1627 ID.AddInteger(TargetFlags); 1628 void *IP = nullptr; 1629 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1630 return SDValue(E, 0); 1631 1632 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1633 TargetFlags); 1634 CSEMap.InsertNode(N, IP); 1635 InsertNode(N); 1636 SDValue V = SDValue(N, 0); 1637 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1638 return V; 1639 } 1640 1641 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1642 MaybeAlign Alignment, int Offset, 1643 bool isTarget, unsigned TargetFlags) { 1644 assert((TargetFlags == 0 || isTarget) && 1645 "Cannot set target flags on target-independent globals"); 1646 if (!Alignment) 1647 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1648 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1649 FoldingSetNodeID ID; 1650 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1651 ID.AddInteger(Alignment->value()); 1652 ID.AddInteger(Offset); 1653 C->addSelectionDAGCSEId(ID); 1654 ID.AddInteger(TargetFlags); 1655 void *IP = nullptr; 1656 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1657 return SDValue(E, 0); 1658 1659 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1660 TargetFlags); 1661 CSEMap.InsertNode(N, IP); 1662 InsertNode(N); 1663 return SDValue(N, 0); 1664 } 1665 1666 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1667 unsigned TargetFlags) { 1668 FoldingSetNodeID ID; 1669 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1670 ID.AddInteger(Index); 1671 ID.AddInteger(Offset); 1672 ID.AddInteger(TargetFlags); 1673 void *IP = nullptr; 1674 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1675 return SDValue(E, 0); 1676 1677 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1678 CSEMap.InsertNode(N, IP); 1679 InsertNode(N); 1680 return SDValue(N, 0); 1681 } 1682 1683 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1684 FoldingSetNodeID ID; 1685 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1686 ID.AddPointer(MBB); 1687 void *IP = nullptr; 1688 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1689 return SDValue(E, 0); 1690 1691 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1692 CSEMap.InsertNode(N, IP); 1693 InsertNode(N); 1694 return SDValue(N, 0); 1695 } 1696 1697 SDValue SelectionDAG::getValueType(EVT VT) { 1698 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1699 ValueTypeNodes.size()) 1700 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1701 1702 SDNode *&N = VT.isExtended() ? 1703 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1704 1705 if (N) return SDValue(N, 0); 1706 N = newSDNode<VTSDNode>(VT); 1707 InsertNode(N); 1708 return SDValue(N, 0); 1709 } 1710 1711 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1712 SDNode *&N = ExternalSymbols[Sym]; 1713 if (N) return SDValue(N, 0); 1714 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1715 InsertNode(N); 1716 return SDValue(N, 0); 1717 } 1718 1719 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1720 SDNode *&N = MCSymbols[Sym]; 1721 if (N) 1722 return SDValue(N, 0); 1723 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1724 InsertNode(N); 1725 return SDValue(N, 0); 1726 } 1727 1728 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1729 unsigned TargetFlags) { 1730 SDNode *&N = 1731 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1732 if (N) return SDValue(N, 0); 1733 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1734 InsertNode(N); 1735 return SDValue(N, 0); 1736 } 1737 1738 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1739 if ((unsigned)Cond >= CondCodeNodes.size()) 1740 CondCodeNodes.resize(Cond+1); 1741 1742 if (!CondCodeNodes[Cond]) { 1743 auto *N = newSDNode<CondCodeSDNode>(Cond); 1744 CondCodeNodes[Cond] = N; 1745 InsertNode(N); 1746 } 1747 1748 return SDValue(CondCodeNodes[Cond], 0); 1749 } 1750 1751 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1752 APInt One(ResVT.getScalarSizeInBits(), 1); 1753 return getStepVector(DL, ResVT, One); 1754 } 1755 1756 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1757 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1758 if (ResVT.isScalableVector()) 1759 return getNode( 1760 ISD::STEP_VECTOR, DL, ResVT, 1761 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1762 1763 SmallVector<SDValue, 16> OpsStepConstants; 1764 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1765 OpsStepConstants.push_back( 1766 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1767 return getBuildVector(ResVT, DL, OpsStepConstants); 1768 } 1769 1770 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1771 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1772 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1773 std::swap(N1, N2); 1774 ShuffleVectorSDNode::commuteMask(M); 1775 } 1776 1777 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1778 SDValue N2, ArrayRef<int> Mask) { 1779 assert(VT.getVectorNumElements() == Mask.size() && 1780 "Must have the same number of vector elements as mask elements!"); 1781 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1782 "Invalid VECTOR_SHUFFLE"); 1783 1784 // Canonicalize shuffle undef, undef -> undef 1785 if (N1.isUndef() && N2.isUndef()) 1786 return getUNDEF(VT); 1787 1788 // Validate that all indices in Mask are within the range of the elements 1789 // input to the shuffle. 1790 int NElts = Mask.size(); 1791 assert(llvm::all_of(Mask, 1792 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1793 "Index out of range"); 1794 1795 // Copy the mask so we can do any needed cleanup. 1796 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1797 1798 // Canonicalize shuffle v, v -> v, undef 1799 if (N1 == N2) { 1800 N2 = getUNDEF(VT); 1801 for (int i = 0; i != NElts; ++i) 1802 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1803 } 1804 1805 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1806 if (N1.isUndef()) 1807 commuteShuffle(N1, N2, MaskVec); 1808 1809 if (TLI->hasVectorBlend()) { 1810 // If shuffling a splat, try to blend the splat instead. We do this here so 1811 // that even when this arises during lowering we don't have to re-handle it. 1812 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1813 BitVector UndefElements; 1814 SDValue Splat = BV->getSplatValue(&UndefElements); 1815 if (!Splat) 1816 return; 1817 1818 for (int i = 0; i < NElts; ++i) { 1819 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1820 continue; 1821 1822 // If this input comes from undef, mark it as such. 1823 if (UndefElements[MaskVec[i] - Offset]) { 1824 MaskVec[i] = -1; 1825 continue; 1826 } 1827 1828 // If we can blend a non-undef lane, use that instead. 1829 if (!UndefElements[i]) 1830 MaskVec[i] = i + Offset; 1831 } 1832 }; 1833 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1834 BlendSplat(N1BV, 0); 1835 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1836 BlendSplat(N2BV, NElts); 1837 } 1838 1839 // Canonicalize all index into lhs, -> shuffle lhs, undef 1840 // Canonicalize all index into rhs, -> shuffle rhs, undef 1841 bool AllLHS = true, AllRHS = true; 1842 bool N2Undef = N2.isUndef(); 1843 for (int i = 0; i != NElts; ++i) { 1844 if (MaskVec[i] >= NElts) { 1845 if (N2Undef) 1846 MaskVec[i] = -1; 1847 else 1848 AllLHS = false; 1849 } else if (MaskVec[i] >= 0) { 1850 AllRHS = false; 1851 } 1852 } 1853 if (AllLHS && AllRHS) 1854 return getUNDEF(VT); 1855 if (AllLHS && !N2Undef) 1856 N2 = getUNDEF(VT); 1857 if (AllRHS) { 1858 N1 = getUNDEF(VT); 1859 commuteShuffle(N1, N2, MaskVec); 1860 } 1861 // Reset our undef status after accounting for the mask. 1862 N2Undef = N2.isUndef(); 1863 // Re-check whether both sides ended up undef. 1864 if (N1.isUndef() && N2Undef) 1865 return getUNDEF(VT); 1866 1867 // If Identity shuffle return that node. 1868 bool Identity = true, AllSame = true; 1869 for (int i = 0; i != NElts; ++i) { 1870 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1871 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1872 } 1873 if (Identity && NElts) 1874 return N1; 1875 1876 // Shuffling a constant splat doesn't change the result. 1877 if (N2Undef) { 1878 SDValue V = N1; 1879 1880 // Look through any bitcasts. We check that these don't change the number 1881 // (and size) of elements and just changes their types. 1882 while (V.getOpcode() == ISD::BITCAST) 1883 V = V->getOperand(0); 1884 1885 // A splat should always show up as a build vector node. 1886 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1887 BitVector UndefElements; 1888 SDValue Splat = BV->getSplatValue(&UndefElements); 1889 // If this is a splat of an undef, shuffling it is also undef. 1890 if (Splat && Splat.isUndef()) 1891 return getUNDEF(VT); 1892 1893 bool SameNumElts = 1894 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1895 1896 // We only have a splat which can skip shuffles if there is a splatted 1897 // value and no undef lanes rearranged by the shuffle. 1898 if (Splat && UndefElements.none()) { 1899 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1900 // number of elements match or the value splatted is a zero constant. 1901 if (SameNumElts) 1902 return N1; 1903 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1904 if (C->isNullValue()) 1905 return N1; 1906 } 1907 1908 // If the shuffle itself creates a splat, build the vector directly. 1909 if (AllSame && SameNumElts) { 1910 EVT BuildVT = BV->getValueType(0); 1911 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1912 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1913 1914 // We may have jumped through bitcasts, so the type of the 1915 // BUILD_VECTOR may not match the type of the shuffle. 1916 if (BuildVT != VT) 1917 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1918 return NewBV; 1919 } 1920 } 1921 } 1922 1923 FoldingSetNodeID ID; 1924 SDValue Ops[2] = { N1, N2 }; 1925 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1926 for (int i = 0; i != NElts; ++i) 1927 ID.AddInteger(MaskVec[i]); 1928 1929 void* IP = nullptr; 1930 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1931 return SDValue(E, 0); 1932 1933 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1934 // SDNode doesn't have access to it. This memory will be "leaked" when 1935 // the node is deallocated, but recovered when the NodeAllocator is released. 1936 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1937 llvm::copy(MaskVec, MaskAlloc); 1938 1939 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1940 dl.getDebugLoc(), MaskAlloc); 1941 createOperands(N, Ops); 1942 1943 CSEMap.InsertNode(N, IP); 1944 InsertNode(N); 1945 SDValue V = SDValue(N, 0); 1946 NewSDValueDbgMsg(V, "Creating new node: ", this); 1947 return V; 1948 } 1949 1950 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1951 EVT VT = SV.getValueType(0); 1952 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1953 ShuffleVectorSDNode::commuteMask(MaskVec); 1954 1955 SDValue Op0 = SV.getOperand(0); 1956 SDValue Op1 = SV.getOperand(1); 1957 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1958 } 1959 1960 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1961 FoldingSetNodeID ID; 1962 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1963 ID.AddInteger(RegNo); 1964 void *IP = nullptr; 1965 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1966 return SDValue(E, 0); 1967 1968 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1969 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1970 CSEMap.InsertNode(N, IP); 1971 InsertNode(N); 1972 return SDValue(N, 0); 1973 } 1974 1975 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1976 FoldingSetNodeID ID; 1977 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1978 ID.AddPointer(RegMask); 1979 void *IP = nullptr; 1980 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1981 return SDValue(E, 0); 1982 1983 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1984 CSEMap.InsertNode(N, IP); 1985 InsertNode(N); 1986 return SDValue(N, 0); 1987 } 1988 1989 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1990 MCSymbol *Label) { 1991 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1992 } 1993 1994 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1995 SDValue Root, MCSymbol *Label) { 1996 FoldingSetNodeID ID; 1997 SDValue Ops[] = { Root }; 1998 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1999 ID.AddPointer(Label); 2000 void *IP = nullptr; 2001 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2002 return SDValue(E, 0); 2003 2004 auto *N = 2005 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2006 createOperands(N, Ops); 2007 2008 CSEMap.InsertNode(N, IP); 2009 InsertNode(N); 2010 return SDValue(N, 0); 2011 } 2012 2013 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2014 int64_t Offset, bool isTarget, 2015 unsigned TargetFlags) { 2016 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2017 2018 FoldingSetNodeID ID; 2019 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2020 ID.AddPointer(BA); 2021 ID.AddInteger(Offset); 2022 ID.AddInteger(TargetFlags); 2023 void *IP = nullptr; 2024 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2025 return SDValue(E, 0); 2026 2027 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2028 CSEMap.InsertNode(N, IP); 2029 InsertNode(N); 2030 return SDValue(N, 0); 2031 } 2032 2033 SDValue SelectionDAG::getSrcValue(const Value *V) { 2034 FoldingSetNodeID ID; 2035 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2036 ID.AddPointer(V); 2037 2038 void *IP = nullptr; 2039 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2040 return SDValue(E, 0); 2041 2042 auto *N = newSDNode<SrcValueSDNode>(V); 2043 CSEMap.InsertNode(N, IP); 2044 InsertNode(N); 2045 return SDValue(N, 0); 2046 } 2047 2048 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2049 FoldingSetNodeID ID; 2050 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2051 ID.AddPointer(MD); 2052 2053 void *IP = nullptr; 2054 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2055 return SDValue(E, 0); 2056 2057 auto *N = newSDNode<MDNodeSDNode>(MD); 2058 CSEMap.InsertNode(N, IP); 2059 InsertNode(N); 2060 return SDValue(N, 0); 2061 } 2062 2063 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2064 if (VT == V.getValueType()) 2065 return V; 2066 2067 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2068 } 2069 2070 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2071 unsigned SrcAS, unsigned DestAS) { 2072 SDValue Ops[] = {Ptr}; 2073 FoldingSetNodeID ID; 2074 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2075 ID.AddInteger(SrcAS); 2076 ID.AddInteger(DestAS); 2077 2078 void *IP = nullptr; 2079 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2080 return SDValue(E, 0); 2081 2082 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2083 VT, SrcAS, DestAS); 2084 createOperands(N, Ops); 2085 2086 CSEMap.InsertNode(N, IP); 2087 InsertNode(N); 2088 return SDValue(N, 0); 2089 } 2090 2091 SDValue SelectionDAG::getFreeze(SDValue V) { 2092 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2093 } 2094 2095 /// getShiftAmountOperand - Return the specified value casted to 2096 /// the target's desired shift amount type. 2097 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2098 EVT OpTy = Op.getValueType(); 2099 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2100 if (OpTy == ShTy || OpTy.isVector()) return Op; 2101 2102 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2103 } 2104 2105 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2106 SDLoc dl(Node); 2107 const TargetLowering &TLI = getTargetLoweringInfo(); 2108 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2109 EVT VT = Node->getValueType(0); 2110 SDValue Tmp1 = Node->getOperand(0); 2111 SDValue Tmp2 = Node->getOperand(1); 2112 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2113 2114 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2115 Tmp2, MachinePointerInfo(V)); 2116 SDValue VAList = VAListLoad; 2117 2118 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2119 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2120 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2121 2122 VAList = 2123 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2124 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2125 } 2126 2127 // Increment the pointer, VAList, to the next vaarg 2128 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2129 getConstant(getDataLayout().getTypeAllocSize( 2130 VT.getTypeForEVT(*getContext())), 2131 dl, VAList.getValueType())); 2132 // Store the incremented VAList to the legalized pointer 2133 Tmp1 = 2134 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2135 // Load the actual argument out of the pointer VAList 2136 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2137 } 2138 2139 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2140 SDLoc dl(Node); 2141 const TargetLowering &TLI = getTargetLoweringInfo(); 2142 // This defaults to loading a pointer from the input and storing it to the 2143 // output, returning the chain. 2144 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2145 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2146 SDValue Tmp1 = 2147 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2148 Node->getOperand(2), MachinePointerInfo(VS)); 2149 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2150 MachinePointerInfo(VD)); 2151 } 2152 2153 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2154 const DataLayout &DL = getDataLayout(); 2155 Type *Ty = VT.getTypeForEVT(*getContext()); 2156 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2157 2158 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2159 return RedAlign; 2160 2161 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2162 const Align StackAlign = TFI->getStackAlign(); 2163 2164 // See if we can choose a smaller ABI alignment in cases where it's an 2165 // illegal vector type that will get broken down. 2166 if (RedAlign > StackAlign) { 2167 EVT IntermediateVT; 2168 MVT RegisterVT; 2169 unsigned NumIntermediates; 2170 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2171 NumIntermediates, RegisterVT); 2172 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2173 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2174 if (RedAlign2 < RedAlign) 2175 RedAlign = RedAlign2; 2176 } 2177 2178 return RedAlign; 2179 } 2180 2181 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2182 MachineFrameInfo &MFI = MF->getFrameInfo(); 2183 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2184 int StackID = 0; 2185 if (Bytes.isScalable()) 2186 StackID = TFI->getStackIDForScalableVectors(); 2187 // The stack id gives an indication of whether the object is scalable or 2188 // not, so it's safe to pass in the minimum size here. 2189 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2190 false, nullptr, StackID); 2191 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2192 } 2193 2194 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2195 Type *Ty = VT.getTypeForEVT(*getContext()); 2196 Align StackAlign = 2197 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2198 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2199 } 2200 2201 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2202 TypeSize VT1Size = VT1.getStoreSize(); 2203 TypeSize VT2Size = VT2.getStoreSize(); 2204 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2205 "Don't know how to choose the maximum size when creating a stack " 2206 "temporary"); 2207 TypeSize Bytes = 2208 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2209 2210 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2211 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2212 const DataLayout &DL = getDataLayout(); 2213 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2214 return CreateStackTemporary(Bytes, Align); 2215 } 2216 2217 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2218 ISD::CondCode Cond, const SDLoc &dl) { 2219 EVT OpVT = N1.getValueType(); 2220 2221 // These setcc operations always fold. 2222 switch (Cond) { 2223 default: break; 2224 case ISD::SETFALSE: 2225 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2226 case ISD::SETTRUE: 2227 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2228 2229 case ISD::SETOEQ: 2230 case ISD::SETOGT: 2231 case ISD::SETOGE: 2232 case ISD::SETOLT: 2233 case ISD::SETOLE: 2234 case ISD::SETONE: 2235 case ISD::SETO: 2236 case ISD::SETUO: 2237 case ISD::SETUEQ: 2238 case ISD::SETUNE: 2239 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2240 break; 2241 } 2242 2243 if (OpVT.isInteger()) { 2244 // For EQ and NE, we can always pick a value for the undef to make the 2245 // predicate pass or fail, so we can return undef. 2246 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2247 // icmp eq/ne X, undef -> undef. 2248 if ((N1.isUndef() || N2.isUndef()) && 2249 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2250 return getUNDEF(VT); 2251 2252 // If both operands are undef, we can return undef for int comparison. 2253 // icmp undef, undef -> undef. 2254 if (N1.isUndef() && N2.isUndef()) 2255 return getUNDEF(VT); 2256 2257 // icmp X, X -> true/false 2258 // icmp X, undef -> true/false because undef could be X. 2259 if (N1 == N2) 2260 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2261 } 2262 2263 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2264 const APInt &C2 = N2C->getAPIntValue(); 2265 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2266 const APInt &C1 = N1C->getAPIntValue(); 2267 2268 switch (Cond) { 2269 default: llvm_unreachable("Unknown integer setcc!"); 2270 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2271 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2272 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2273 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2274 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2275 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2276 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2277 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2278 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2279 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2280 } 2281 } 2282 } 2283 2284 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2285 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2286 2287 if (N1CFP && N2CFP) { 2288 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2289 switch (Cond) { 2290 default: break; 2291 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2292 return getUNDEF(VT); 2293 LLVM_FALLTHROUGH; 2294 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2295 OpVT); 2296 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2297 return getUNDEF(VT); 2298 LLVM_FALLTHROUGH; 2299 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2300 R==APFloat::cmpLessThan, dl, VT, 2301 OpVT); 2302 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2303 return getUNDEF(VT); 2304 LLVM_FALLTHROUGH; 2305 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2306 OpVT); 2307 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2308 return getUNDEF(VT); 2309 LLVM_FALLTHROUGH; 2310 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2311 VT, OpVT); 2312 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2313 return getUNDEF(VT); 2314 LLVM_FALLTHROUGH; 2315 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2316 R==APFloat::cmpEqual, dl, VT, 2317 OpVT); 2318 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2319 return getUNDEF(VT); 2320 LLVM_FALLTHROUGH; 2321 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2322 R==APFloat::cmpEqual, dl, VT, OpVT); 2323 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2324 OpVT); 2325 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2326 OpVT); 2327 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2328 R==APFloat::cmpEqual, dl, VT, 2329 OpVT); 2330 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2331 OpVT); 2332 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2333 R==APFloat::cmpLessThan, dl, VT, 2334 OpVT); 2335 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2336 R==APFloat::cmpUnordered, dl, VT, 2337 OpVT); 2338 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2339 VT, OpVT); 2340 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2341 OpVT); 2342 } 2343 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2344 // Ensure that the constant occurs on the RHS. 2345 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2346 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2347 return SDValue(); 2348 return getSetCC(dl, VT, N2, N1, SwappedCond); 2349 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2350 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2351 // If an operand is known to be a nan (or undef that could be a nan), we can 2352 // fold it. 2353 // Choosing NaN for the undef will always make unordered comparison succeed 2354 // and ordered comparison fails. 2355 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2356 switch (ISD::getUnorderedFlavor(Cond)) { 2357 default: 2358 llvm_unreachable("Unknown flavor!"); 2359 case 0: // Known false. 2360 return getBoolConstant(false, dl, VT, OpVT); 2361 case 1: // Known true. 2362 return getBoolConstant(true, dl, VT, OpVT); 2363 case 2: // Undefined. 2364 return getUNDEF(VT); 2365 } 2366 } 2367 2368 // Could not fold it. 2369 return SDValue(); 2370 } 2371 2372 /// See if the specified operand can be simplified with the knowledge that only 2373 /// the bits specified by DemandedBits are used. 2374 /// TODO: really we should be making this into the DAG equivalent of 2375 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2376 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2377 EVT VT = V.getValueType(); 2378 2379 if (VT.isScalableVector()) 2380 return SDValue(); 2381 2382 APInt DemandedElts = VT.isVector() 2383 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2384 : APInt(1, 1); 2385 return GetDemandedBits(V, DemandedBits, DemandedElts); 2386 } 2387 2388 /// See if the specified operand can be simplified with the knowledge that only 2389 /// the bits specified by DemandedBits are used in the elements specified by 2390 /// DemandedElts. 2391 /// TODO: really we should be making this into the DAG equivalent of 2392 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2393 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2394 const APInt &DemandedElts) { 2395 switch (V.getOpcode()) { 2396 default: 2397 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2398 *this, 0); 2399 case ISD::Constant: { 2400 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2401 APInt NewVal = CVal & DemandedBits; 2402 if (NewVal != CVal) 2403 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2404 break; 2405 } 2406 case ISD::SRL: 2407 // Only look at single-use SRLs. 2408 if (!V.getNode()->hasOneUse()) 2409 break; 2410 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2411 // See if we can recursively simplify the LHS. 2412 unsigned Amt = RHSC->getZExtValue(); 2413 2414 // Watch out for shift count overflow though. 2415 if (Amt >= DemandedBits.getBitWidth()) 2416 break; 2417 APInt SrcDemandedBits = DemandedBits << Amt; 2418 if (SDValue SimplifyLHS = 2419 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2420 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2421 V.getOperand(1)); 2422 } 2423 break; 2424 } 2425 return SDValue(); 2426 } 2427 2428 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2429 /// use this predicate to simplify operations downstream. 2430 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2431 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2432 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2433 } 2434 2435 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2436 /// this predicate to simplify operations downstream. Mask is known to be zero 2437 /// for bits that V cannot have. 2438 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2439 unsigned Depth) const { 2440 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2441 } 2442 2443 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2444 /// DemandedElts. We use this predicate to simplify operations downstream. 2445 /// Mask is known to be zero for bits that V cannot have. 2446 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2447 const APInt &DemandedElts, 2448 unsigned Depth) const { 2449 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2450 } 2451 2452 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2453 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2454 unsigned Depth) const { 2455 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2456 } 2457 2458 /// isSplatValue - Return true if the vector V has the same value 2459 /// across all DemandedElts. For scalable vectors it does not make 2460 /// sense to specify which elements are demanded or undefined, therefore 2461 /// they are simply ignored. 2462 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2463 APInt &UndefElts, unsigned Depth) { 2464 EVT VT = V.getValueType(); 2465 assert(VT.isVector() && "Vector type expected"); 2466 2467 if (!VT.isScalableVector() && !DemandedElts) 2468 return false; // No demanded elts, better to assume we don't know anything. 2469 2470 if (Depth >= MaxRecursionDepth) 2471 return false; // Limit search depth. 2472 2473 // Deal with some common cases here that work for both fixed and scalable 2474 // vector types. 2475 switch (V.getOpcode()) { 2476 case ISD::SPLAT_VECTOR: 2477 UndefElts = V.getOperand(0).isUndef() 2478 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2479 : APInt(DemandedElts.getBitWidth(), 0); 2480 return true; 2481 case ISD::ADD: 2482 case ISD::SUB: 2483 case ISD::AND: 2484 case ISD::XOR: 2485 case ISD::OR: { 2486 APInt UndefLHS, UndefRHS; 2487 SDValue LHS = V.getOperand(0); 2488 SDValue RHS = V.getOperand(1); 2489 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2490 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2491 UndefElts = UndefLHS | UndefRHS; 2492 return true; 2493 } 2494 return false; 2495 } 2496 case ISD::ABS: 2497 case ISD::TRUNCATE: 2498 case ISD::SIGN_EXTEND: 2499 case ISD::ZERO_EXTEND: 2500 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2501 } 2502 2503 // We don't support other cases than those above for scalable vectors at 2504 // the moment. 2505 if (VT.isScalableVector()) 2506 return false; 2507 2508 unsigned NumElts = VT.getVectorNumElements(); 2509 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2510 UndefElts = APInt::getNullValue(NumElts); 2511 2512 switch (V.getOpcode()) { 2513 case ISD::BUILD_VECTOR: { 2514 SDValue Scl; 2515 for (unsigned i = 0; i != NumElts; ++i) { 2516 SDValue Op = V.getOperand(i); 2517 if (Op.isUndef()) { 2518 UndefElts.setBit(i); 2519 continue; 2520 } 2521 if (!DemandedElts[i]) 2522 continue; 2523 if (Scl && Scl != Op) 2524 return false; 2525 Scl = Op; 2526 } 2527 return true; 2528 } 2529 case ISD::VECTOR_SHUFFLE: { 2530 // Check if this is a shuffle node doing a splat. 2531 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2532 int SplatIndex = -1; 2533 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2534 for (int i = 0; i != (int)NumElts; ++i) { 2535 int M = Mask[i]; 2536 if (M < 0) { 2537 UndefElts.setBit(i); 2538 continue; 2539 } 2540 if (!DemandedElts[i]) 2541 continue; 2542 if (0 <= SplatIndex && SplatIndex != M) 2543 return false; 2544 SplatIndex = M; 2545 } 2546 return true; 2547 } 2548 case ISD::EXTRACT_SUBVECTOR: { 2549 // Offset the demanded elts by the subvector index. 2550 SDValue Src = V.getOperand(0); 2551 // We don't support scalable vectors at the moment. 2552 if (Src.getValueType().isScalableVector()) 2553 return false; 2554 uint64_t Idx = V.getConstantOperandVal(1); 2555 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2556 APInt UndefSrcElts; 2557 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2558 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2559 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2560 return true; 2561 } 2562 break; 2563 } 2564 } 2565 2566 return false; 2567 } 2568 2569 /// Helper wrapper to main isSplatValue function. 2570 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2571 EVT VT = V.getValueType(); 2572 assert(VT.isVector() && "Vector type expected"); 2573 2574 APInt UndefElts; 2575 APInt DemandedElts; 2576 2577 // For now we don't support this with scalable vectors. 2578 if (!VT.isScalableVector()) 2579 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2580 return isSplatValue(V, DemandedElts, UndefElts) && 2581 (AllowUndefs || !UndefElts); 2582 } 2583 2584 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2585 V = peekThroughExtractSubvectors(V); 2586 2587 EVT VT = V.getValueType(); 2588 unsigned Opcode = V.getOpcode(); 2589 switch (Opcode) { 2590 default: { 2591 APInt UndefElts; 2592 APInt DemandedElts; 2593 2594 if (!VT.isScalableVector()) 2595 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2596 2597 if (isSplatValue(V, DemandedElts, UndefElts)) { 2598 if (VT.isScalableVector()) { 2599 // DemandedElts and UndefElts are ignored for scalable vectors, since 2600 // the only supported cases are SPLAT_VECTOR nodes. 2601 SplatIdx = 0; 2602 } else { 2603 // Handle case where all demanded elements are UNDEF. 2604 if (DemandedElts.isSubsetOf(UndefElts)) { 2605 SplatIdx = 0; 2606 return getUNDEF(VT); 2607 } 2608 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2609 } 2610 return V; 2611 } 2612 break; 2613 } 2614 case ISD::SPLAT_VECTOR: 2615 SplatIdx = 0; 2616 return V; 2617 case ISD::VECTOR_SHUFFLE: { 2618 if (VT.isScalableVector()) 2619 return SDValue(); 2620 2621 // Check if this is a shuffle node doing a splat. 2622 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2623 // getTargetVShiftNode currently struggles without the splat source. 2624 auto *SVN = cast<ShuffleVectorSDNode>(V); 2625 if (!SVN->isSplat()) 2626 break; 2627 int Idx = SVN->getSplatIndex(); 2628 int NumElts = V.getValueType().getVectorNumElements(); 2629 SplatIdx = Idx % NumElts; 2630 return V.getOperand(Idx / NumElts); 2631 } 2632 } 2633 2634 return SDValue(); 2635 } 2636 2637 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2638 int SplatIdx; 2639 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2640 EVT SVT = SrcVector.getValueType().getScalarType(); 2641 EVT LegalSVT = SVT; 2642 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2643 if (!SVT.isInteger()) 2644 return SDValue(); 2645 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2646 if (LegalSVT.bitsLT(SVT)) 2647 return SDValue(); 2648 } 2649 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2650 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2651 } 2652 return SDValue(); 2653 } 2654 2655 const APInt * 2656 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2657 const APInt &DemandedElts) const { 2658 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2659 V.getOpcode() == ISD::SRA) && 2660 "Unknown shift node"); 2661 unsigned BitWidth = V.getScalarValueSizeInBits(); 2662 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2663 // Shifting more than the bitwidth is not valid. 2664 const APInt &ShAmt = SA->getAPIntValue(); 2665 if (ShAmt.ult(BitWidth)) 2666 return &ShAmt; 2667 } 2668 return nullptr; 2669 } 2670 2671 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2672 SDValue V, const APInt &DemandedElts) const { 2673 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2674 V.getOpcode() == ISD::SRA) && 2675 "Unknown shift node"); 2676 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2677 return ValidAmt; 2678 unsigned BitWidth = V.getScalarValueSizeInBits(); 2679 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2680 if (!BV) 2681 return nullptr; 2682 const APInt *MinShAmt = nullptr; 2683 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2684 if (!DemandedElts[i]) 2685 continue; 2686 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2687 if (!SA) 2688 return nullptr; 2689 // Shifting more than the bitwidth is not valid. 2690 const APInt &ShAmt = SA->getAPIntValue(); 2691 if (ShAmt.uge(BitWidth)) 2692 return nullptr; 2693 if (MinShAmt && MinShAmt->ule(ShAmt)) 2694 continue; 2695 MinShAmt = &ShAmt; 2696 } 2697 return MinShAmt; 2698 } 2699 2700 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2701 SDValue V, const APInt &DemandedElts) const { 2702 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2703 V.getOpcode() == ISD::SRA) && 2704 "Unknown shift node"); 2705 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2706 return ValidAmt; 2707 unsigned BitWidth = V.getScalarValueSizeInBits(); 2708 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2709 if (!BV) 2710 return nullptr; 2711 const APInt *MaxShAmt = nullptr; 2712 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2713 if (!DemandedElts[i]) 2714 continue; 2715 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2716 if (!SA) 2717 return nullptr; 2718 // Shifting more than the bitwidth is not valid. 2719 const APInt &ShAmt = SA->getAPIntValue(); 2720 if (ShAmt.uge(BitWidth)) 2721 return nullptr; 2722 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2723 continue; 2724 MaxShAmt = &ShAmt; 2725 } 2726 return MaxShAmt; 2727 } 2728 2729 /// Determine which bits of Op are known to be either zero or one and return 2730 /// them in Known. For vectors, the known bits are those that are shared by 2731 /// every vector element. 2732 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2733 EVT VT = Op.getValueType(); 2734 2735 // TOOD: Until we have a plan for how to represent demanded elements for 2736 // scalable vectors, we can just bail out for now. 2737 if (Op.getValueType().isScalableVector()) { 2738 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2739 return KnownBits(BitWidth); 2740 } 2741 2742 APInt DemandedElts = VT.isVector() 2743 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2744 : APInt(1, 1); 2745 return computeKnownBits(Op, DemandedElts, Depth); 2746 } 2747 2748 /// Determine which bits of Op are known to be either zero or one and return 2749 /// them in Known. The DemandedElts argument allows us to only collect the known 2750 /// bits that are shared by the requested vector elements. 2751 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2752 unsigned Depth) const { 2753 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2754 2755 KnownBits Known(BitWidth); // Don't know anything. 2756 2757 // TOOD: Until we have a plan for how to represent demanded elements for 2758 // scalable vectors, we can just bail out for now. 2759 if (Op.getValueType().isScalableVector()) 2760 return Known; 2761 2762 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2763 // We know all of the bits for a constant! 2764 return KnownBits::makeConstant(C->getAPIntValue()); 2765 } 2766 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2767 // We know all of the bits for a constant fp! 2768 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2769 } 2770 2771 if (Depth >= MaxRecursionDepth) 2772 return Known; // Limit search depth. 2773 2774 KnownBits Known2; 2775 unsigned NumElts = DemandedElts.getBitWidth(); 2776 assert((!Op.getValueType().isVector() || 2777 NumElts == Op.getValueType().getVectorNumElements()) && 2778 "Unexpected vector size"); 2779 2780 if (!DemandedElts) 2781 return Known; // No demanded elts, better to assume we don't know anything. 2782 2783 unsigned Opcode = Op.getOpcode(); 2784 switch (Opcode) { 2785 case ISD::BUILD_VECTOR: 2786 // Collect the known bits that are shared by every demanded vector element. 2787 Known.Zero.setAllBits(); Known.One.setAllBits(); 2788 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2789 if (!DemandedElts[i]) 2790 continue; 2791 2792 SDValue SrcOp = Op.getOperand(i); 2793 Known2 = computeKnownBits(SrcOp, Depth + 1); 2794 2795 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2796 if (SrcOp.getValueSizeInBits() != BitWidth) { 2797 assert(SrcOp.getValueSizeInBits() > BitWidth && 2798 "Expected BUILD_VECTOR implicit truncation"); 2799 Known2 = Known2.trunc(BitWidth); 2800 } 2801 2802 // Known bits are the values that are shared by every demanded element. 2803 Known = KnownBits::commonBits(Known, Known2); 2804 2805 // If we don't know any bits, early out. 2806 if (Known.isUnknown()) 2807 break; 2808 } 2809 break; 2810 case ISD::VECTOR_SHUFFLE: { 2811 // Collect the known bits that are shared by every vector element referenced 2812 // by the shuffle. 2813 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2814 Known.Zero.setAllBits(); Known.One.setAllBits(); 2815 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2816 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2817 for (unsigned i = 0; i != NumElts; ++i) { 2818 if (!DemandedElts[i]) 2819 continue; 2820 2821 int M = SVN->getMaskElt(i); 2822 if (M < 0) { 2823 // For UNDEF elements, we don't know anything about the common state of 2824 // the shuffle result. 2825 Known.resetAll(); 2826 DemandedLHS.clearAllBits(); 2827 DemandedRHS.clearAllBits(); 2828 break; 2829 } 2830 2831 if ((unsigned)M < NumElts) 2832 DemandedLHS.setBit((unsigned)M % NumElts); 2833 else 2834 DemandedRHS.setBit((unsigned)M % NumElts); 2835 } 2836 // Known bits are the values that are shared by every demanded element. 2837 if (!!DemandedLHS) { 2838 SDValue LHS = Op.getOperand(0); 2839 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2840 Known = KnownBits::commonBits(Known, Known2); 2841 } 2842 // If we don't know any bits, early out. 2843 if (Known.isUnknown()) 2844 break; 2845 if (!!DemandedRHS) { 2846 SDValue RHS = Op.getOperand(1); 2847 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2848 Known = KnownBits::commonBits(Known, Known2); 2849 } 2850 break; 2851 } 2852 case ISD::CONCAT_VECTORS: { 2853 // Split DemandedElts and test each of the demanded subvectors. 2854 Known.Zero.setAllBits(); Known.One.setAllBits(); 2855 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2856 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2857 unsigned NumSubVectors = Op.getNumOperands(); 2858 for (unsigned i = 0; i != NumSubVectors; ++i) { 2859 APInt DemandedSub = 2860 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2861 if (!!DemandedSub) { 2862 SDValue Sub = Op.getOperand(i); 2863 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2864 Known = KnownBits::commonBits(Known, Known2); 2865 } 2866 // If we don't know any bits, early out. 2867 if (Known.isUnknown()) 2868 break; 2869 } 2870 break; 2871 } 2872 case ISD::INSERT_SUBVECTOR: { 2873 // Demand any elements from the subvector and the remainder from the src its 2874 // inserted into. 2875 SDValue Src = Op.getOperand(0); 2876 SDValue Sub = Op.getOperand(1); 2877 uint64_t Idx = Op.getConstantOperandVal(2); 2878 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2879 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2880 APInt DemandedSrcElts = DemandedElts; 2881 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2882 2883 Known.One.setAllBits(); 2884 Known.Zero.setAllBits(); 2885 if (!!DemandedSubElts) { 2886 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2887 if (Known.isUnknown()) 2888 break; // early-out. 2889 } 2890 if (!!DemandedSrcElts) { 2891 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2892 Known = KnownBits::commonBits(Known, Known2); 2893 } 2894 break; 2895 } 2896 case ISD::EXTRACT_SUBVECTOR: { 2897 // Offset the demanded elts by the subvector index. 2898 SDValue Src = Op.getOperand(0); 2899 // Bail until we can represent demanded elements for scalable vectors. 2900 if (Src.getValueType().isScalableVector()) 2901 break; 2902 uint64_t Idx = Op.getConstantOperandVal(1); 2903 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2904 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2905 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2906 break; 2907 } 2908 case ISD::SCALAR_TO_VECTOR: { 2909 // We know about scalar_to_vector as much as we know about it source, 2910 // which becomes the first element of otherwise unknown vector. 2911 if (DemandedElts != 1) 2912 break; 2913 2914 SDValue N0 = Op.getOperand(0); 2915 Known = computeKnownBits(N0, Depth + 1); 2916 if (N0.getValueSizeInBits() != BitWidth) 2917 Known = Known.trunc(BitWidth); 2918 2919 break; 2920 } 2921 case ISD::BITCAST: { 2922 SDValue N0 = Op.getOperand(0); 2923 EVT SubVT = N0.getValueType(); 2924 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2925 2926 // Ignore bitcasts from unsupported types. 2927 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2928 break; 2929 2930 // Fast handling of 'identity' bitcasts. 2931 if (BitWidth == SubBitWidth) { 2932 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2933 break; 2934 } 2935 2936 bool IsLE = getDataLayout().isLittleEndian(); 2937 2938 // Bitcast 'small element' vector to 'large element' scalar/vector. 2939 if ((BitWidth % SubBitWidth) == 0) { 2940 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2941 2942 // Collect known bits for the (larger) output by collecting the known 2943 // bits from each set of sub elements and shift these into place. 2944 // We need to separately call computeKnownBits for each set of 2945 // sub elements as the knownbits for each is likely to be different. 2946 unsigned SubScale = BitWidth / SubBitWidth; 2947 APInt SubDemandedElts(NumElts * SubScale, 0); 2948 for (unsigned i = 0; i != NumElts; ++i) 2949 if (DemandedElts[i]) 2950 SubDemandedElts.setBit(i * SubScale); 2951 2952 for (unsigned i = 0; i != SubScale; ++i) { 2953 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2954 Depth + 1); 2955 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2956 Known.insertBits(Known2, SubBitWidth * Shifts); 2957 } 2958 } 2959 2960 // Bitcast 'large element' scalar/vector to 'small element' vector. 2961 if ((SubBitWidth % BitWidth) == 0) { 2962 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2963 2964 // Collect known bits for the (smaller) output by collecting the known 2965 // bits from the overlapping larger input elements and extracting the 2966 // sub sections we actually care about. 2967 unsigned SubScale = SubBitWidth / BitWidth; 2968 APInt SubDemandedElts(NumElts / SubScale, 0); 2969 for (unsigned i = 0; i != NumElts; ++i) 2970 if (DemandedElts[i]) 2971 SubDemandedElts.setBit(i / SubScale); 2972 2973 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2974 2975 Known.Zero.setAllBits(); Known.One.setAllBits(); 2976 for (unsigned i = 0; i != NumElts; ++i) 2977 if (DemandedElts[i]) { 2978 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2979 unsigned Offset = (Shifts % SubScale) * BitWidth; 2980 Known = KnownBits::commonBits(Known, 2981 Known2.extractBits(BitWidth, Offset)); 2982 // If we don't know any bits, early out. 2983 if (Known.isUnknown()) 2984 break; 2985 } 2986 } 2987 break; 2988 } 2989 case ISD::AND: 2990 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2991 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2992 2993 Known &= Known2; 2994 break; 2995 case ISD::OR: 2996 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2997 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2998 2999 Known |= Known2; 3000 break; 3001 case ISD::XOR: 3002 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3003 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3004 3005 Known ^= Known2; 3006 break; 3007 case ISD::MUL: { 3008 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3009 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3010 Known = KnownBits::mul(Known, Known2); 3011 break; 3012 } 3013 case ISD::MULHU: { 3014 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3015 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3016 Known = KnownBits::mulhu(Known, Known2); 3017 break; 3018 } 3019 case ISD::MULHS: { 3020 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3021 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3022 Known = KnownBits::mulhs(Known, Known2); 3023 break; 3024 } 3025 case ISD::UMUL_LOHI: { 3026 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3027 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3028 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3029 if (Op.getResNo() == 0) 3030 Known = KnownBits::mul(Known, Known2); 3031 else 3032 Known = KnownBits::mulhu(Known, Known2); 3033 break; 3034 } 3035 case ISD::SMUL_LOHI: { 3036 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3037 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3038 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3039 if (Op.getResNo() == 0) 3040 Known = KnownBits::mul(Known, Known2); 3041 else 3042 Known = KnownBits::mulhs(Known, Known2); 3043 break; 3044 } 3045 case ISD::UDIV: { 3046 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3047 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3048 Known = KnownBits::udiv(Known, Known2); 3049 break; 3050 } 3051 case ISD::SELECT: 3052 case ISD::VSELECT: 3053 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3054 // If we don't know any bits, early out. 3055 if (Known.isUnknown()) 3056 break; 3057 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3058 3059 // Only known if known in both the LHS and RHS. 3060 Known = KnownBits::commonBits(Known, Known2); 3061 break; 3062 case ISD::SELECT_CC: 3063 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3064 // If we don't know any bits, early out. 3065 if (Known.isUnknown()) 3066 break; 3067 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3068 3069 // Only known if known in both the LHS and RHS. 3070 Known = KnownBits::commonBits(Known, Known2); 3071 break; 3072 case ISD::SMULO: 3073 case ISD::UMULO: 3074 if (Op.getResNo() != 1) 3075 break; 3076 // The boolean result conforms to getBooleanContents. 3077 // If we know the result of a setcc has the top bits zero, use this info. 3078 // We know that we have an integer-based boolean since these operations 3079 // are only available for integer. 3080 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3081 TargetLowering::ZeroOrOneBooleanContent && 3082 BitWidth > 1) 3083 Known.Zero.setBitsFrom(1); 3084 break; 3085 case ISD::SETCC: 3086 case ISD::STRICT_FSETCC: 3087 case ISD::STRICT_FSETCCS: { 3088 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3089 // If we know the result of a setcc has the top bits zero, use this info. 3090 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3091 TargetLowering::ZeroOrOneBooleanContent && 3092 BitWidth > 1) 3093 Known.Zero.setBitsFrom(1); 3094 break; 3095 } 3096 case ISD::SHL: 3097 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3098 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3099 Known = KnownBits::shl(Known, Known2); 3100 3101 // Minimum shift low bits are known zero. 3102 if (const APInt *ShMinAmt = 3103 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3104 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3105 break; 3106 case ISD::SRL: 3107 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3108 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3109 Known = KnownBits::lshr(Known, Known2); 3110 3111 // Minimum shift high bits are known zero. 3112 if (const APInt *ShMinAmt = 3113 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3114 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3115 break; 3116 case ISD::SRA: 3117 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3118 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3119 Known = KnownBits::ashr(Known, Known2); 3120 // TODO: Add minimum shift high known sign bits. 3121 break; 3122 case ISD::FSHL: 3123 case ISD::FSHR: 3124 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3125 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3126 3127 // For fshl, 0-shift returns the 1st arg. 3128 // For fshr, 0-shift returns the 2nd arg. 3129 if (Amt == 0) { 3130 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3131 DemandedElts, Depth + 1); 3132 break; 3133 } 3134 3135 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3136 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3137 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3138 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3139 if (Opcode == ISD::FSHL) { 3140 Known.One <<= Amt; 3141 Known.Zero <<= Amt; 3142 Known2.One.lshrInPlace(BitWidth - Amt); 3143 Known2.Zero.lshrInPlace(BitWidth - Amt); 3144 } else { 3145 Known.One <<= BitWidth - Amt; 3146 Known.Zero <<= BitWidth - Amt; 3147 Known2.One.lshrInPlace(Amt); 3148 Known2.Zero.lshrInPlace(Amt); 3149 } 3150 Known.One |= Known2.One; 3151 Known.Zero |= Known2.Zero; 3152 } 3153 break; 3154 case ISD::SIGN_EXTEND_INREG: { 3155 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3156 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3157 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3158 break; 3159 } 3160 case ISD::CTTZ: 3161 case ISD::CTTZ_ZERO_UNDEF: { 3162 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3163 // If we have a known 1, its position is our upper bound. 3164 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3165 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3166 Known.Zero.setBitsFrom(LowBits); 3167 break; 3168 } 3169 case ISD::CTLZ: 3170 case ISD::CTLZ_ZERO_UNDEF: { 3171 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3172 // If we have a known 1, its position is our upper bound. 3173 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3174 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3175 Known.Zero.setBitsFrom(LowBits); 3176 break; 3177 } 3178 case ISD::CTPOP: { 3179 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3180 // If we know some of the bits are zero, they can't be one. 3181 unsigned PossibleOnes = Known2.countMaxPopulation(); 3182 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3183 break; 3184 } 3185 case ISD::PARITY: { 3186 // Parity returns 0 everywhere but the LSB. 3187 Known.Zero.setBitsFrom(1); 3188 break; 3189 } 3190 case ISD::LOAD: { 3191 LoadSDNode *LD = cast<LoadSDNode>(Op); 3192 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3193 if (ISD::isNON_EXTLoad(LD) && Cst) { 3194 // Determine any common known bits from the loaded constant pool value. 3195 Type *CstTy = Cst->getType(); 3196 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3197 // If its a vector splat, then we can (quickly) reuse the scalar path. 3198 // NOTE: We assume all elements match and none are UNDEF. 3199 if (CstTy->isVectorTy()) { 3200 if (const Constant *Splat = Cst->getSplatValue()) { 3201 Cst = Splat; 3202 CstTy = Cst->getType(); 3203 } 3204 } 3205 // TODO - do we need to handle different bitwidths? 3206 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3207 // Iterate across all vector elements finding common known bits. 3208 Known.One.setAllBits(); 3209 Known.Zero.setAllBits(); 3210 for (unsigned i = 0; i != NumElts; ++i) { 3211 if (!DemandedElts[i]) 3212 continue; 3213 if (Constant *Elt = Cst->getAggregateElement(i)) { 3214 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3215 const APInt &Value = CInt->getValue(); 3216 Known.One &= Value; 3217 Known.Zero &= ~Value; 3218 continue; 3219 } 3220 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3221 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3222 Known.One &= Value; 3223 Known.Zero &= ~Value; 3224 continue; 3225 } 3226 } 3227 Known.One.clearAllBits(); 3228 Known.Zero.clearAllBits(); 3229 break; 3230 } 3231 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3232 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3233 Known = KnownBits::makeConstant(CInt->getValue()); 3234 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3235 Known = 3236 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3237 } 3238 } 3239 } 3240 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3241 // If this is a ZEXTLoad and we are looking at the loaded value. 3242 EVT VT = LD->getMemoryVT(); 3243 unsigned MemBits = VT.getScalarSizeInBits(); 3244 Known.Zero.setBitsFrom(MemBits); 3245 } else if (const MDNode *Ranges = LD->getRanges()) { 3246 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3247 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3248 } 3249 break; 3250 } 3251 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3252 EVT InVT = Op.getOperand(0).getValueType(); 3253 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3254 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3255 Known = Known.zext(BitWidth); 3256 break; 3257 } 3258 case ISD::ZERO_EXTEND: { 3259 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3260 Known = Known.zext(BitWidth); 3261 break; 3262 } 3263 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3264 EVT InVT = Op.getOperand(0).getValueType(); 3265 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3266 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3267 // If the sign bit is known to be zero or one, then sext will extend 3268 // it to the top bits, else it will just zext. 3269 Known = Known.sext(BitWidth); 3270 break; 3271 } 3272 case ISD::SIGN_EXTEND: { 3273 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3274 // If the sign bit is known to be zero or one, then sext will extend 3275 // it to the top bits, else it will just zext. 3276 Known = Known.sext(BitWidth); 3277 break; 3278 } 3279 case ISD::ANY_EXTEND_VECTOR_INREG: { 3280 EVT InVT = Op.getOperand(0).getValueType(); 3281 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3282 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3283 Known = Known.anyext(BitWidth); 3284 break; 3285 } 3286 case ISD::ANY_EXTEND: { 3287 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3288 Known = Known.anyext(BitWidth); 3289 break; 3290 } 3291 case ISD::TRUNCATE: { 3292 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3293 Known = Known.trunc(BitWidth); 3294 break; 3295 } 3296 case ISD::AssertZext: { 3297 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3298 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3299 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3300 Known.Zero |= (~InMask); 3301 Known.One &= (~Known.Zero); 3302 break; 3303 } 3304 case ISD::AssertAlign: { 3305 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3306 assert(LogOfAlign != 0); 3307 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3308 // well as clearing one bits. 3309 Known.Zero.setLowBits(LogOfAlign); 3310 Known.One.clearLowBits(LogOfAlign); 3311 break; 3312 } 3313 case ISD::FGETSIGN: 3314 // All bits are zero except the low bit. 3315 Known.Zero.setBitsFrom(1); 3316 break; 3317 case ISD::USUBO: 3318 case ISD::SSUBO: 3319 if (Op.getResNo() == 1) { 3320 // If we know the result of a setcc has the top bits zero, use this info. 3321 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3322 TargetLowering::ZeroOrOneBooleanContent && 3323 BitWidth > 1) 3324 Known.Zero.setBitsFrom(1); 3325 break; 3326 } 3327 LLVM_FALLTHROUGH; 3328 case ISD::SUB: 3329 case ISD::SUBC: { 3330 assert(Op.getResNo() == 0 && 3331 "We only compute knownbits for the difference here."); 3332 3333 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3334 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3335 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3336 Known, Known2); 3337 break; 3338 } 3339 case ISD::UADDO: 3340 case ISD::SADDO: 3341 case ISD::ADDCARRY: 3342 if (Op.getResNo() == 1) { 3343 // If we know the result of a setcc has the top bits zero, use this info. 3344 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3345 TargetLowering::ZeroOrOneBooleanContent && 3346 BitWidth > 1) 3347 Known.Zero.setBitsFrom(1); 3348 break; 3349 } 3350 LLVM_FALLTHROUGH; 3351 case ISD::ADD: 3352 case ISD::ADDC: 3353 case ISD::ADDE: { 3354 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3355 3356 // With ADDE and ADDCARRY, a carry bit may be added in. 3357 KnownBits Carry(1); 3358 if (Opcode == ISD::ADDE) 3359 // Can't track carry from glue, set carry to unknown. 3360 Carry.resetAll(); 3361 else if (Opcode == ISD::ADDCARRY) 3362 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3363 // the trouble (how often will we find a known carry bit). And I haven't 3364 // tested this very much yet, but something like this might work: 3365 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3366 // Carry = Carry.zextOrTrunc(1, false); 3367 Carry.resetAll(); 3368 else 3369 Carry.setAllZero(); 3370 3371 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3372 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3373 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3374 break; 3375 } 3376 case ISD::SREM: { 3377 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3378 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3379 Known = KnownBits::srem(Known, Known2); 3380 break; 3381 } 3382 case ISD::UREM: { 3383 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3384 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3385 Known = KnownBits::urem(Known, Known2); 3386 break; 3387 } 3388 case ISD::EXTRACT_ELEMENT: { 3389 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3390 const unsigned Index = Op.getConstantOperandVal(1); 3391 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3392 3393 // Remove low part of known bits mask 3394 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3395 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3396 3397 // Remove high part of known bit mask 3398 Known = Known.trunc(EltBitWidth); 3399 break; 3400 } 3401 case ISD::EXTRACT_VECTOR_ELT: { 3402 SDValue InVec = Op.getOperand(0); 3403 SDValue EltNo = Op.getOperand(1); 3404 EVT VecVT = InVec.getValueType(); 3405 // computeKnownBits not yet implemented for scalable vectors. 3406 if (VecVT.isScalableVector()) 3407 break; 3408 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3409 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3410 3411 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3412 // anything about the extended bits. 3413 if (BitWidth > EltBitWidth) 3414 Known = Known.trunc(EltBitWidth); 3415 3416 // If we know the element index, just demand that vector element, else for 3417 // an unknown element index, ignore DemandedElts and demand them all. 3418 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3419 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3420 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3421 DemandedSrcElts = 3422 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3423 3424 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3425 if (BitWidth > EltBitWidth) 3426 Known = Known.anyext(BitWidth); 3427 break; 3428 } 3429 case ISD::INSERT_VECTOR_ELT: { 3430 // If we know the element index, split the demand between the 3431 // source vector and the inserted element, otherwise assume we need 3432 // the original demanded vector elements and the value. 3433 SDValue InVec = Op.getOperand(0); 3434 SDValue InVal = Op.getOperand(1); 3435 SDValue EltNo = Op.getOperand(2); 3436 bool DemandedVal = true; 3437 APInt DemandedVecElts = DemandedElts; 3438 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3439 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3440 unsigned EltIdx = CEltNo->getZExtValue(); 3441 DemandedVal = !!DemandedElts[EltIdx]; 3442 DemandedVecElts.clearBit(EltIdx); 3443 } 3444 Known.One.setAllBits(); 3445 Known.Zero.setAllBits(); 3446 if (DemandedVal) { 3447 Known2 = computeKnownBits(InVal, Depth + 1); 3448 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3449 } 3450 if (!!DemandedVecElts) { 3451 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3452 Known = KnownBits::commonBits(Known, Known2); 3453 } 3454 break; 3455 } 3456 case ISD::BITREVERSE: { 3457 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3458 Known = Known2.reverseBits(); 3459 break; 3460 } 3461 case ISD::BSWAP: { 3462 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3463 Known = Known2.byteSwap(); 3464 break; 3465 } 3466 case ISD::ABS: { 3467 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3468 Known = Known2.abs(); 3469 break; 3470 } 3471 case ISD::USUBSAT: { 3472 // The result of usubsat will never be larger than the LHS. 3473 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3474 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3475 break; 3476 } 3477 case ISD::UMIN: { 3478 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3479 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3480 Known = KnownBits::umin(Known, Known2); 3481 break; 3482 } 3483 case ISD::UMAX: { 3484 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3485 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3486 Known = KnownBits::umax(Known, Known2); 3487 break; 3488 } 3489 case ISD::SMIN: 3490 case ISD::SMAX: { 3491 // If we have a clamp pattern, we know that the number of sign bits will be 3492 // the minimum of the clamp min/max range. 3493 bool IsMax = (Opcode == ISD::SMAX); 3494 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3495 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3496 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3497 CstHigh = 3498 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3499 if (CstLow && CstHigh) { 3500 if (!IsMax) 3501 std::swap(CstLow, CstHigh); 3502 3503 const APInt &ValueLow = CstLow->getAPIntValue(); 3504 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3505 if (ValueLow.sle(ValueHigh)) { 3506 unsigned LowSignBits = ValueLow.getNumSignBits(); 3507 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3508 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3509 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3510 Known.One.setHighBits(MinSignBits); 3511 break; 3512 } 3513 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3514 Known.Zero.setHighBits(MinSignBits); 3515 break; 3516 } 3517 } 3518 } 3519 3520 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3521 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3522 if (IsMax) 3523 Known = KnownBits::smax(Known, Known2); 3524 else 3525 Known = KnownBits::smin(Known, Known2); 3526 break; 3527 } 3528 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3529 if (Op.getResNo() == 1) { 3530 // The boolean result conforms to getBooleanContents. 3531 // If we know the result of a setcc has the top bits zero, use this info. 3532 // We know that we have an integer-based boolean since these operations 3533 // are only available for integer. 3534 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3535 TargetLowering::ZeroOrOneBooleanContent && 3536 BitWidth > 1) 3537 Known.Zero.setBitsFrom(1); 3538 break; 3539 } 3540 LLVM_FALLTHROUGH; 3541 case ISD::ATOMIC_CMP_SWAP: 3542 case ISD::ATOMIC_SWAP: 3543 case ISD::ATOMIC_LOAD_ADD: 3544 case ISD::ATOMIC_LOAD_SUB: 3545 case ISD::ATOMIC_LOAD_AND: 3546 case ISD::ATOMIC_LOAD_CLR: 3547 case ISD::ATOMIC_LOAD_OR: 3548 case ISD::ATOMIC_LOAD_XOR: 3549 case ISD::ATOMIC_LOAD_NAND: 3550 case ISD::ATOMIC_LOAD_MIN: 3551 case ISD::ATOMIC_LOAD_MAX: 3552 case ISD::ATOMIC_LOAD_UMIN: 3553 case ISD::ATOMIC_LOAD_UMAX: 3554 case ISD::ATOMIC_LOAD: { 3555 unsigned MemBits = 3556 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3557 // If we are looking at the loaded value. 3558 if (Op.getResNo() == 0) { 3559 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3560 Known.Zero.setBitsFrom(MemBits); 3561 } 3562 break; 3563 } 3564 case ISD::FrameIndex: 3565 case ISD::TargetFrameIndex: 3566 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3567 Known, getMachineFunction()); 3568 break; 3569 3570 default: 3571 if (Opcode < ISD::BUILTIN_OP_END) 3572 break; 3573 LLVM_FALLTHROUGH; 3574 case ISD::INTRINSIC_WO_CHAIN: 3575 case ISD::INTRINSIC_W_CHAIN: 3576 case ISD::INTRINSIC_VOID: 3577 // Allow the target to implement this method for its nodes. 3578 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3579 break; 3580 } 3581 3582 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3583 return Known; 3584 } 3585 3586 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3587 SDValue N1) const { 3588 // X + 0 never overflow 3589 if (isNullConstant(N1)) 3590 return OFK_Never; 3591 3592 KnownBits N1Known = computeKnownBits(N1); 3593 if (N1Known.Zero.getBoolValue()) { 3594 KnownBits N0Known = computeKnownBits(N0); 3595 3596 bool overflow; 3597 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3598 if (!overflow) 3599 return OFK_Never; 3600 } 3601 3602 // mulhi + 1 never overflow 3603 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3604 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3605 return OFK_Never; 3606 3607 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3608 KnownBits N0Known = computeKnownBits(N0); 3609 3610 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3611 return OFK_Never; 3612 } 3613 3614 return OFK_Sometime; 3615 } 3616 3617 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3618 EVT OpVT = Val.getValueType(); 3619 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3620 3621 // Is the constant a known power of 2? 3622 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3623 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3624 3625 // A left-shift of a constant one will have exactly one bit set because 3626 // shifting the bit off the end is undefined. 3627 if (Val.getOpcode() == ISD::SHL) { 3628 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3629 if (C && C->getAPIntValue() == 1) 3630 return true; 3631 } 3632 3633 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3634 // one bit set. 3635 if (Val.getOpcode() == ISD::SRL) { 3636 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3637 if (C && C->getAPIntValue().isSignMask()) 3638 return true; 3639 } 3640 3641 // Are all operands of a build vector constant powers of two? 3642 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3643 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3644 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3645 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3646 return false; 3647 })) 3648 return true; 3649 3650 // More could be done here, though the above checks are enough 3651 // to handle some common cases. 3652 3653 // Fall back to computeKnownBits to catch other known cases. 3654 KnownBits Known = computeKnownBits(Val); 3655 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3656 } 3657 3658 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3659 EVT VT = Op.getValueType(); 3660 3661 // TODO: Assume we don't know anything for now. 3662 if (VT.isScalableVector()) 3663 return 1; 3664 3665 APInt DemandedElts = VT.isVector() 3666 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3667 : APInt(1, 1); 3668 return ComputeNumSignBits(Op, DemandedElts, Depth); 3669 } 3670 3671 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3672 unsigned Depth) const { 3673 EVT VT = Op.getValueType(); 3674 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3675 unsigned VTBits = VT.getScalarSizeInBits(); 3676 unsigned NumElts = DemandedElts.getBitWidth(); 3677 unsigned Tmp, Tmp2; 3678 unsigned FirstAnswer = 1; 3679 3680 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3681 const APInt &Val = C->getAPIntValue(); 3682 return Val.getNumSignBits(); 3683 } 3684 3685 if (Depth >= MaxRecursionDepth) 3686 return 1; // Limit search depth. 3687 3688 if (!DemandedElts || VT.isScalableVector()) 3689 return 1; // No demanded elts, better to assume we don't know anything. 3690 3691 unsigned Opcode = Op.getOpcode(); 3692 switch (Opcode) { 3693 default: break; 3694 case ISD::AssertSext: 3695 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3696 return VTBits-Tmp+1; 3697 case ISD::AssertZext: 3698 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3699 return VTBits-Tmp; 3700 3701 case ISD::BUILD_VECTOR: 3702 Tmp = VTBits; 3703 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3704 if (!DemandedElts[i]) 3705 continue; 3706 3707 SDValue SrcOp = Op.getOperand(i); 3708 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3709 3710 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3711 if (SrcOp.getValueSizeInBits() != VTBits) { 3712 assert(SrcOp.getValueSizeInBits() > VTBits && 3713 "Expected BUILD_VECTOR implicit truncation"); 3714 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3715 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3716 } 3717 Tmp = std::min(Tmp, Tmp2); 3718 } 3719 return Tmp; 3720 3721 case ISD::VECTOR_SHUFFLE: { 3722 // Collect the minimum number of sign bits that are shared by every vector 3723 // element referenced by the shuffle. 3724 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3725 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3726 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3727 for (unsigned i = 0; i != NumElts; ++i) { 3728 int M = SVN->getMaskElt(i); 3729 if (!DemandedElts[i]) 3730 continue; 3731 // For UNDEF elements, we don't know anything about the common state of 3732 // the shuffle result. 3733 if (M < 0) 3734 return 1; 3735 if ((unsigned)M < NumElts) 3736 DemandedLHS.setBit((unsigned)M % NumElts); 3737 else 3738 DemandedRHS.setBit((unsigned)M % NumElts); 3739 } 3740 Tmp = std::numeric_limits<unsigned>::max(); 3741 if (!!DemandedLHS) 3742 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3743 if (!!DemandedRHS) { 3744 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3745 Tmp = std::min(Tmp, Tmp2); 3746 } 3747 // If we don't know anything, early out and try computeKnownBits fall-back. 3748 if (Tmp == 1) 3749 break; 3750 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3751 return Tmp; 3752 } 3753 3754 case ISD::BITCAST: { 3755 SDValue N0 = Op.getOperand(0); 3756 EVT SrcVT = N0.getValueType(); 3757 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3758 3759 // Ignore bitcasts from unsupported types.. 3760 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3761 break; 3762 3763 // Fast handling of 'identity' bitcasts. 3764 if (VTBits == SrcBits) 3765 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3766 3767 bool IsLE = getDataLayout().isLittleEndian(); 3768 3769 // Bitcast 'large element' scalar/vector to 'small element' vector. 3770 if ((SrcBits % VTBits) == 0) { 3771 assert(VT.isVector() && "Expected bitcast to vector"); 3772 3773 unsigned Scale = SrcBits / VTBits; 3774 APInt SrcDemandedElts(NumElts / Scale, 0); 3775 for (unsigned i = 0; i != NumElts; ++i) 3776 if (DemandedElts[i]) 3777 SrcDemandedElts.setBit(i / Scale); 3778 3779 // Fast case - sign splat can be simply split across the small elements. 3780 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3781 if (Tmp == SrcBits) 3782 return VTBits; 3783 3784 // Slow case - determine how far the sign extends into each sub-element. 3785 Tmp2 = VTBits; 3786 for (unsigned i = 0; i != NumElts; ++i) 3787 if (DemandedElts[i]) { 3788 unsigned SubOffset = i % Scale; 3789 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3790 SubOffset = SubOffset * VTBits; 3791 if (Tmp <= SubOffset) 3792 return 1; 3793 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3794 } 3795 return Tmp2; 3796 } 3797 break; 3798 } 3799 3800 case ISD::SIGN_EXTEND: 3801 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3802 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3803 case ISD::SIGN_EXTEND_INREG: 3804 // Max of the input and what this extends. 3805 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3806 Tmp = VTBits-Tmp+1; 3807 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3808 return std::max(Tmp, Tmp2); 3809 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3810 SDValue Src = Op.getOperand(0); 3811 EVT SrcVT = Src.getValueType(); 3812 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3813 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3814 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3815 } 3816 case ISD::SRA: 3817 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3818 // SRA X, C -> adds C sign bits. 3819 if (const APInt *ShAmt = 3820 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3821 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3822 return Tmp; 3823 case ISD::SHL: 3824 if (const APInt *ShAmt = 3825 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3826 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3827 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3828 if (ShAmt->ult(Tmp)) 3829 return Tmp - ShAmt->getZExtValue(); 3830 } 3831 break; 3832 case ISD::AND: 3833 case ISD::OR: 3834 case ISD::XOR: // NOT is handled here. 3835 // Logical binary ops preserve the number of sign bits at the worst. 3836 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3837 if (Tmp != 1) { 3838 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3839 FirstAnswer = std::min(Tmp, Tmp2); 3840 // We computed what we know about the sign bits as our first 3841 // answer. Now proceed to the generic code that uses 3842 // computeKnownBits, and pick whichever answer is better. 3843 } 3844 break; 3845 3846 case ISD::SELECT: 3847 case ISD::VSELECT: 3848 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3849 if (Tmp == 1) return 1; // Early out. 3850 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3851 return std::min(Tmp, Tmp2); 3852 case ISD::SELECT_CC: 3853 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3854 if (Tmp == 1) return 1; // Early out. 3855 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3856 return std::min(Tmp, Tmp2); 3857 3858 case ISD::SMIN: 3859 case ISD::SMAX: { 3860 // If we have a clamp pattern, we know that the number of sign bits will be 3861 // the minimum of the clamp min/max range. 3862 bool IsMax = (Opcode == ISD::SMAX); 3863 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3864 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3865 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3866 CstHigh = 3867 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3868 if (CstLow && CstHigh) { 3869 if (!IsMax) 3870 std::swap(CstLow, CstHigh); 3871 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3872 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3873 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3874 return std::min(Tmp, Tmp2); 3875 } 3876 } 3877 3878 // Fallback - just get the minimum number of sign bits of the operands. 3879 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3880 if (Tmp == 1) 3881 return 1; // Early out. 3882 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3883 return std::min(Tmp, Tmp2); 3884 } 3885 case ISD::UMIN: 3886 case ISD::UMAX: 3887 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3888 if (Tmp == 1) 3889 return 1; // Early out. 3890 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3891 return std::min(Tmp, Tmp2); 3892 case ISD::SADDO: 3893 case ISD::UADDO: 3894 case ISD::SSUBO: 3895 case ISD::USUBO: 3896 case ISD::SMULO: 3897 case ISD::UMULO: 3898 if (Op.getResNo() != 1) 3899 break; 3900 // The boolean result conforms to getBooleanContents. Fall through. 3901 // If setcc returns 0/-1, all bits are sign bits. 3902 // We know that we have an integer-based boolean since these operations 3903 // are only available for integer. 3904 if (TLI->getBooleanContents(VT.isVector(), false) == 3905 TargetLowering::ZeroOrNegativeOneBooleanContent) 3906 return VTBits; 3907 break; 3908 case ISD::SETCC: 3909 case ISD::STRICT_FSETCC: 3910 case ISD::STRICT_FSETCCS: { 3911 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3912 // If setcc returns 0/-1, all bits are sign bits. 3913 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3914 TargetLowering::ZeroOrNegativeOneBooleanContent) 3915 return VTBits; 3916 break; 3917 } 3918 case ISD::ROTL: 3919 case ISD::ROTR: 3920 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3921 3922 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3923 if (Tmp == VTBits) 3924 return VTBits; 3925 3926 if (ConstantSDNode *C = 3927 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3928 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3929 3930 // Handle rotate right by N like a rotate left by 32-N. 3931 if (Opcode == ISD::ROTR) 3932 RotAmt = (VTBits - RotAmt) % VTBits; 3933 3934 // If we aren't rotating out all of the known-in sign bits, return the 3935 // number that are left. This handles rotl(sext(x), 1) for example. 3936 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3937 } 3938 break; 3939 case ISD::ADD: 3940 case ISD::ADDC: 3941 // Add can have at most one carry bit. Thus we know that the output 3942 // is, at worst, one more bit than the inputs. 3943 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3944 if (Tmp == 1) return 1; // Early out. 3945 3946 // Special case decrementing a value (ADD X, -1): 3947 if (ConstantSDNode *CRHS = 3948 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3949 if (CRHS->isAllOnesValue()) { 3950 KnownBits Known = 3951 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3952 3953 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3954 // sign bits set. 3955 if ((Known.Zero | 1).isAllOnesValue()) 3956 return VTBits; 3957 3958 // If we are subtracting one from a positive number, there is no carry 3959 // out of the result. 3960 if (Known.isNonNegative()) 3961 return Tmp; 3962 } 3963 3964 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3965 if (Tmp2 == 1) return 1; // Early out. 3966 return std::min(Tmp, Tmp2) - 1; 3967 case ISD::SUB: 3968 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3969 if (Tmp2 == 1) return 1; // Early out. 3970 3971 // Handle NEG. 3972 if (ConstantSDNode *CLHS = 3973 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3974 if (CLHS->isNullValue()) { 3975 KnownBits Known = 3976 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3977 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3978 // sign bits set. 3979 if ((Known.Zero | 1).isAllOnesValue()) 3980 return VTBits; 3981 3982 // If the input is known to be positive (the sign bit is known clear), 3983 // the output of the NEG has the same number of sign bits as the input. 3984 if (Known.isNonNegative()) 3985 return Tmp2; 3986 3987 // Otherwise, we treat this like a SUB. 3988 } 3989 3990 // Sub can have at most one carry bit. Thus we know that the output 3991 // is, at worst, one more bit than the inputs. 3992 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3993 if (Tmp == 1) return 1; // Early out. 3994 return std::min(Tmp, Tmp2) - 1; 3995 case ISD::MUL: { 3996 // The output of the Mul can be at most twice the valid bits in the inputs. 3997 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3998 if (SignBitsOp0 == 1) 3999 break; 4000 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4001 if (SignBitsOp1 == 1) 4002 break; 4003 unsigned OutValidBits = 4004 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4005 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4006 } 4007 case ISD::SREM: 4008 // The sign bit is the LHS's sign bit, except when the result of the 4009 // remainder is zero. The magnitude of the result should be less than or 4010 // equal to the magnitude of the LHS. Therefore, the result should have 4011 // at least as many sign bits as the left hand side. 4012 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4013 case ISD::TRUNCATE: { 4014 // Check if the sign bits of source go down as far as the truncated value. 4015 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4016 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4017 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4018 return NumSrcSignBits - (NumSrcBits - VTBits); 4019 break; 4020 } 4021 case ISD::EXTRACT_ELEMENT: { 4022 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4023 const int BitWidth = Op.getValueSizeInBits(); 4024 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4025 4026 // Get reverse index (starting from 1), Op1 value indexes elements from 4027 // little end. Sign starts at big end. 4028 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4029 4030 // If the sign portion ends in our element the subtraction gives correct 4031 // result. Otherwise it gives either negative or > bitwidth result 4032 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4033 } 4034 case ISD::INSERT_VECTOR_ELT: { 4035 // If we know the element index, split the demand between the 4036 // source vector and the inserted element, otherwise assume we need 4037 // the original demanded vector elements and the value. 4038 SDValue InVec = Op.getOperand(0); 4039 SDValue InVal = Op.getOperand(1); 4040 SDValue EltNo = Op.getOperand(2); 4041 bool DemandedVal = true; 4042 APInt DemandedVecElts = DemandedElts; 4043 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4044 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4045 unsigned EltIdx = CEltNo->getZExtValue(); 4046 DemandedVal = !!DemandedElts[EltIdx]; 4047 DemandedVecElts.clearBit(EltIdx); 4048 } 4049 Tmp = std::numeric_limits<unsigned>::max(); 4050 if (DemandedVal) { 4051 // TODO - handle implicit truncation of inserted elements. 4052 if (InVal.getScalarValueSizeInBits() != VTBits) 4053 break; 4054 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4055 Tmp = std::min(Tmp, Tmp2); 4056 } 4057 if (!!DemandedVecElts) { 4058 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4059 Tmp = std::min(Tmp, Tmp2); 4060 } 4061 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4062 return Tmp; 4063 } 4064 case ISD::EXTRACT_VECTOR_ELT: { 4065 SDValue InVec = Op.getOperand(0); 4066 SDValue EltNo = Op.getOperand(1); 4067 EVT VecVT = InVec.getValueType(); 4068 // ComputeNumSignBits not yet implemented for scalable vectors. 4069 if (VecVT.isScalableVector()) 4070 break; 4071 const unsigned BitWidth = Op.getValueSizeInBits(); 4072 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4073 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4074 4075 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4076 // anything about sign bits. But if the sizes match we can derive knowledge 4077 // about sign bits from the vector operand. 4078 if (BitWidth != EltBitWidth) 4079 break; 4080 4081 // If we know the element index, just demand that vector element, else for 4082 // an unknown element index, ignore DemandedElts and demand them all. 4083 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 4084 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4085 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4086 DemandedSrcElts = 4087 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4088 4089 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4090 } 4091 case ISD::EXTRACT_SUBVECTOR: { 4092 // Offset the demanded elts by the subvector index. 4093 SDValue Src = Op.getOperand(0); 4094 // Bail until we can represent demanded elements for scalable vectors. 4095 if (Src.getValueType().isScalableVector()) 4096 break; 4097 uint64_t Idx = Op.getConstantOperandVal(1); 4098 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4099 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4100 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4101 } 4102 case ISD::CONCAT_VECTORS: { 4103 // Determine the minimum number of sign bits across all demanded 4104 // elts of the input vectors. Early out if the result is already 1. 4105 Tmp = std::numeric_limits<unsigned>::max(); 4106 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4107 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4108 unsigned NumSubVectors = Op.getNumOperands(); 4109 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4110 APInt DemandedSub = 4111 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4112 if (!DemandedSub) 4113 continue; 4114 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4115 Tmp = std::min(Tmp, Tmp2); 4116 } 4117 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4118 return Tmp; 4119 } 4120 case ISD::INSERT_SUBVECTOR: { 4121 // Demand any elements from the subvector and the remainder from the src its 4122 // inserted into. 4123 SDValue Src = Op.getOperand(0); 4124 SDValue Sub = Op.getOperand(1); 4125 uint64_t Idx = Op.getConstantOperandVal(2); 4126 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4127 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4128 APInt DemandedSrcElts = DemandedElts; 4129 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 4130 4131 Tmp = std::numeric_limits<unsigned>::max(); 4132 if (!!DemandedSubElts) { 4133 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4134 if (Tmp == 1) 4135 return 1; // early-out 4136 } 4137 if (!!DemandedSrcElts) { 4138 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4139 Tmp = std::min(Tmp, Tmp2); 4140 } 4141 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4142 return Tmp; 4143 } 4144 case ISD::ATOMIC_CMP_SWAP: 4145 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4146 case ISD::ATOMIC_SWAP: 4147 case ISD::ATOMIC_LOAD_ADD: 4148 case ISD::ATOMIC_LOAD_SUB: 4149 case ISD::ATOMIC_LOAD_AND: 4150 case ISD::ATOMIC_LOAD_CLR: 4151 case ISD::ATOMIC_LOAD_OR: 4152 case ISD::ATOMIC_LOAD_XOR: 4153 case ISD::ATOMIC_LOAD_NAND: 4154 case ISD::ATOMIC_LOAD_MIN: 4155 case ISD::ATOMIC_LOAD_MAX: 4156 case ISD::ATOMIC_LOAD_UMIN: 4157 case ISD::ATOMIC_LOAD_UMAX: 4158 case ISD::ATOMIC_LOAD: { 4159 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4160 // If we are looking at the loaded value. 4161 if (Op.getResNo() == 0) { 4162 if (Tmp == VTBits) 4163 return 1; // early-out 4164 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4165 return VTBits - Tmp + 1; 4166 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4167 return VTBits - Tmp; 4168 } 4169 break; 4170 } 4171 } 4172 4173 // If we are looking at the loaded value of the SDNode. 4174 if (Op.getResNo() == 0) { 4175 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4176 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4177 unsigned ExtType = LD->getExtensionType(); 4178 switch (ExtType) { 4179 default: break; 4180 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4181 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4182 return VTBits - Tmp + 1; 4183 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4184 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4185 return VTBits - Tmp; 4186 case ISD::NON_EXTLOAD: 4187 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4188 // We only need to handle vectors - computeKnownBits should handle 4189 // scalar cases. 4190 Type *CstTy = Cst->getType(); 4191 if (CstTy->isVectorTy() && 4192 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4193 Tmp = VTBits; 4194 for (unsigned i = 0; i != NumElts; ++i) { 4195 if (!DemandedElts[i]) 4196 continue; 4197 if (Constant *Elt = Cst->getAggregateElement(i)) { 4198 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4199 const APInt &Value = CInt->getValue(); 4200 Tmp = std::min(Tmp, Value.getNumSignBits()); 4201 continue; 4202 } 4203 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4204 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4205 Tmp = std::min(Tmp, Value.getNumSignBits()); 4206 continue; 4207 } 4208 } 4209 // Unknown type. Conservatively assume no bits match sign bit. 4210 return 1; 4211 } 4212 return Tmp; 4213 } 4214 } 4215 break; 4216 } 4217 } 4218 } 4219 4220 // Allow the target to implement this method for its nodes. 4221 if (Opcode >= ISD::BUILTIN_OP_END || 4222 Opcode == ISD::INTRINSIC_WO_CHAIN || 4223 Opcode == ISD::INTRINSIC_W_CHAIN || 4224 Opcode == ISD::INTRINSIC_VOID) { 4225 unsigned NumBits = 4226 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4227 if (NumBits > 1) 4228 FirstAnswer = std::max(FirstAnswer, NumBits); 4229 } 4230 4231 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4232 // use this information. 4233 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4234 4235 APInt Mask; 4236 if (Known.isNonNegative()) { // sign bit is 0 4237 Mask = Known.Zero; 4238 } else if (Known.isNegative()) { // sign bit is 1; 4239 Mask = Known.One; 4240 } else { 4241 // Nothing known. 4242 return FirstAnswer; 4243 } 4244 4245 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4246 // the number of identical bits in the top of the input value. 4247 Mask <<= Mask.getBitWidth()-VTBits; 4248 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4249 } 4250 4251 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4252 unsigned Depth) const { 4253 // Early out for FREEZE. 4254 if (Op.getOpcode() == ISD::FREEZE) 4255 return true; 4256 4257 // TODO: Assume we don't know anything for now. 4258 EVT VT = Op.getValueType(); 4259 if (VT.isScalableVector()) 4260 return false; 4261 4262 APInt DemandedElts = VT.isVector() 4263 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 4264 : APInt(1, 1); 4265 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4266 } 4267 4268 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4269 const APInt &DemandedElts, 4270 bool PoisonOnly, 4271 unsigned Depth) const { 4272 unsigned Opcode = Op.getOpcode(); 4273 4274 // Early out for FREEZE. 4275 if (Opcode == ISD::FREEZE) 4276 return true; 4277 4278 if (Depth >= MaxRecursionDepth) 4279 return false; // Limit search depth. 4280 4281 if (isIntOrFPConstant(Op)) 4282 return true; 4283 4284 switch (Opcode) { 4285 case ISD::UNDEF: 4286 return PoisonOnly; 4287 4288 case ISD::BUILD_VECTOR: 4289 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4290 // this shouldn't affect the result. 4291 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4292 if (!DemandedElts[i]) 4293 continue; 4294 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4295 Depth + 1)) 4296 return false; 4297 } 4298 return true; 4299 4300 // TODO: Search for noundef attributes from library functions. 4301 4302 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4303 4304 default: 4305 // Allow the target to implement this method for its nodes. 4306 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4307 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4308 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4309 Op, DemandedElts, *this, PoisonOnly, Depth); 4310 break; 4311 } 4312 4313 return false; 4314 } 4315 4316 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4317 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4318 !isa<ConstantSDNode>(Op.getOperand(1))) 4319 return false; 4320 4321 if (Op.getOpcode() == ISD::OR && 4322 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4323 return false; 4324 4325 return true; 4326 } 4327 4328 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4329 // If we're told that NaNs won't happen, assume they won't. 4330 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4331 return true; 4332 4333 if (Depth >= MaxRecursionDepth) 4334 return false; // Limit search depth. 4335 4336 // TODO: Handle vectors. 4337 // If the value is a constant, we can obviously see if it is a NaN or not. 4338 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4339 return !C->getValueAPF().isNaN() || 4340 (SNaN && !C->getValueAPF().isSignaling()); 4341 } 4342 4343 unsigned Opcode = Op.getOpcode(); 4344 switch (Opcode) { 4345 case ISD::FADD: 4346 case ISD::FSUB: 4347 case ISD::FMUL: 4348 case ISD::FDIV: 4349 case ISD::FREM: 4350 case ISD::FSIN: 4351 case ISD::FCOS: { 4352 if (SNaN) 4353 return true; 4354 // TODO: Need isKnownNeverInfinity 4355 return false; 4356 } 4357 case ISD::FCANONICALIZE: 4358 case ISD::FEXP: 4359 case ISD::FEXP2: 4360 case ISD::FTRUNC: 4361 case ISD::FFLOOR: 4362 case ISD::FCEIL: 4363 case ISD::FROUND: 4364 case ISD::FROUNDEVEN: 4365 case ISD::FRINT: 4366 case ISD::FNEARBYINT: { 4367 if (SNaN) 4368 return true; 4369 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4370 } 4371 case ISD::FABS: 4372 case ISD::FNEG: 4373 case ISD::FCOPYSIGN: { 4374 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4375 } 4376 case ISD::SELECT: 4377 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4378 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4379 case ISD::FP_EXTEND: 4380 case ISD::FP_ROUND: { 4381 if (SNaN) 4382 return true; 4383 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4384 } 4385 case ISD::SINT_TO_FP: 4386 case ISD::UINT_TO_FP: 4387 return true; 4388 case ISD::FMA: 4389 case ISD::FMAD: { 4390 if (SNaN) 4391 return true; 4392 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4393 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4394 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4395 } 4396 case ISD::FSQRT: // Need is known positive 4397 case ISD::FLOG: 4398 case ISD::FLOG2: 4399 case ISD::FLOG10: 4400 case ISD::FPOWI: 4401 case ISD::FPOW: { 4402 if (SNaN) 4403 return true; 4404 // TODO: Refine on operand 4405 return false; 4406 } 4407 case ISD::FMINNUM: 4408 case ISD::FMAXNUM: { 4409 // Only one needs to be known not-nan, since it will be returned if the 4410 // other ends up being one. 4411 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4412 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4413 } 4414 case ISD::FMINNUM_IEEE: 4415 case ISD::FMAXNUM_IEEE: { 4416 if (SNaN) 4417 return true; 4418 // This can return a NaN if either operand is an sNaN, or if both operands 4419 // are NaN. 4420 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4421 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4422 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4423 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4424 } 4425 case ISD::FMINIMUM: 4426 case ISD::FMAXIMUM: { 4427 // TODO: Does this quiet or return the origina NaN as-is? 4428 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4429 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4430 } 4431 case ISD::EXTRACT_VECTOR_ELT: { 4432 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4433 } 4434 default: 4435 if (Opcode >= ISD::BUILTIN_OP_END || 4436 Opcode == ISD::INTRINSIC_WO_CHAIN || 4437 Opcode == ISD::INTRINSIC_W_CHAIN || 4438 Opcode == ISD::INTRINSIC_VOID) { 4439 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4440 } 4441 4442 return false; 4443 } 4444 } 4445 4446 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4447 assert(Op.getValueType().isFloatingPoint() && 4448 "Floating point type expected"); 4449 4450 // If the value is a constant, we can obviously see if it is a zero or not. 4451 // TODO: Add BuildVector support. 4452 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4453 return !C->isZero(); 4454 return false; 4455 } 4456 4457 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4458 assert(!Op.getValueType().isFloatingPoint() && 4459 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4460 4461 // If the value is a constant, we can obviously see if it is a zero or not. 4462 if (ISD::matchUnaryPredicate( 4463 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4464 return true; 4465 4466 // TODO: Recognize more cases here. 4467 switch (Op.getOpcode()) { 4468 default: break; 4469 case ISD::OR: 4470 if (isKnownNeverZero(Op.getOperand(1)) || 4471 isKnownNeverZero(Op.getOperand(0))) 4472 return true; 4473 break; 4474 } 4475 4476 return false; 4477 } 4478 4479 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4480 // Check the obvious case. 4481 if (A == B) return true; 4482 4483 // For for negative and positive zero. 4484 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4485 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4486 if (CA->isZero() && CB->isZero()) return true; 4487 4488 // Otherwise they may not be equal. 4489 return false; 4490 } 4491 4492 // FIXME: unify with llvm::haveNoCommonBitsSet. 4493 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4494 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4495 assert(A.getValueType() == B.getValueType() && 4496 "Values must have the same type"); 4497 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4498 computeKnownBits(B)); 4499 } 4500 4501 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4502 SelectionDAG &DAG) { 4503 if (cast<ConstantSDNode>(Step)->isNullValue()) 4504 return DAG.getConstant(0, DL, VT); 4505 4506 return SDValue(); 4507 } 4508 4509 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4510 ArrayRef<SDValue> Ops, 4511 SelectionDAG &DAG) { 4512 int NumOps = Ops.size(); 4513 assert(NumOps != 0 && "Can't build an empty vector!"); 4514 assert(!VT.isScalableVector() && 4515 "BUILD_VECTOR cannot be used with scalable types"); 4516 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4517 "Incorrect element count in BUILD_VECTOR!"); 4518 4519 // BUILD_VECTOR of UNDEFs is UNDEF. 4520 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4521 return DAG.getUNDEF(VT); 4522 4523 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4524 SDValue IdentitySrc; 4525 bool IsIdentity = true; 4526 for (int i = 0; i != NumOps; ++i) { 4527 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4528 Ops[i].getOperand(0).getValueType() != VT || 4529 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4530 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4531 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4532 IsIdentity = false; 4533 break; 4534 } 4535 IdentitySrc = Ops[i].getOperand(0); 4536 } 4537 if (IsIdentity) 4538 return IdentitySrc; 4539 4540 return SDValue(); 4541 } 4542 4543 /// Try to simplify vector concatenation to an input value, undef, or build 4544 /// vector. 4545 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4546 ArrayRef<SDValue> Ops, 4547 SelectionDAG &DAG) { 4548 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4549 assert(llvm::all_of(Ops, 4550 [Ops](SDValue Op) { 4551 return Ops[0].getValueType() == Op.getValueType(); 4552 }) && 4553 "Concatenation of vectors with inconsistent value types!"); 4554 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4555 VT.getVectorElementCount() && 4556 "Incorrect element count in vector concatenation!"); 4557 4558 if (Ops.size() == 1) 4559 return Ops[0]; 4560 4561 // Concat of UNDEFs is UNDEF. 4562 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4563 return DAG.getUNDEF(VT); 4564 4565 // Scan the operands and look for extract operations from a single source 4566 // that correspond to insertion at the same location via this concatenation: 4567 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4568 SDValue IdentitySrc; 4569 bool IsIdentity = true; 4570 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4571 SDValue Op = Ops[i]; 4572 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4573 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4574 Op.getOperand(0).getValueType() != VT || 4575 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4576 Op.getConstantOperandVal(1) != IdentityIndex) { 4577 IsIdentity = false; 4578 break; 4579 } 4580 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4581 "Unexpected identity source vector for concat of extracts"); 4582 IdentitySrc = Op.getOperand(0); 4583 } 4584 if (IsIdentity) { 4585 assert(IdentitySrc && "Failed to set source vector of extracts"); 4586 return IdentitySrc; 4587 } 4588 4589 // The code below this point is only designed to work for fixed width 4590 // vectors, so we bail out for now. 4591 if (VT.isScalableVector()) 4592 return SDValue(); 4593 4594 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4595 // simplified to one big BUILD_VECTOR. 4596 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4597 EVT SVT = VT.getScalarType(); 4598 SmallVector<SDValue, 16> Elts; 4599 for (SDValue Op : Ops) { 4600 EVT OpVT = Op.getValueType(); 4601 if (Op.isUndef()) 4602 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4603 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4604 Elts.append(Op->op_begin(), Op->op_end()); 4605 else 4606 return SDValue(); 4607 } 4608 4609 // BUILD_VECTOR requires all inputs to be of the same type, find the 4610 // maximum type and extend them all. 4611 for (SDValue Op : Elts) 4612 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4613 4614 if (SVT.bitsGT(VT.getScalarType())) { 4615 for (SDValue &Op : Elts) { 4616 if (Op.isUndef()) 4617 Op = DAG.getUNDEF(SVT); 4618 else 4619 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4620 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4621 : DAG.getSExtOrTrunc(Op, DL, SVT); 4622 } 4623 } 4624 4625 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4626 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4627 return V; 4628 } 4629 4630 /// Gets or creates the specified node. 4631 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4632 FoldingSetNodeID ID; 4633 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4634 void *IP = nullptr; 4635 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4636 return SDValue(E, 0); 4637 4638 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4639 getVTList(VT)); 4640 CSEMap.InsertNode(N, IP); 4641 4642 InsertNode(N); 4643 SDValue V = SDValue(N, 0); 4644 NewSDValueDbgMsg(V, "Creating new node: ", this); 4645 return V; 4646 } 4647 4648 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4649 SDValue Operand) { 4650 SDNodeFlags Flags; 4651 if (Inserter) 4652 Flags = Inserter->getFlags(); 4653 return getNode(Opcode, DL, VT, Operand, Flags); 4654 } 4655 4656 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4657 SDValue Operand, const SDNodeFlags Flags) { 4658 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4659 "Operand is DELETED_NODE!"); 4660 // Constant fold unary operations with an integer constant operand. Even 4661 // opaque constant will be folded, because the folding of unary operations 4662 // doesn't create new constants with different values. Nevertheless, the 4663 // opaque flag is preserved during folding to prevent future folding with 4664 // other constants. 4665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4666 const APInt &Val = C->getAPIntValue(); 4667 switch (Opcode) { 4668 default: break; 4669 case ISD::SIGN_EXTEND: 4670 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4671 C->isTargetOpcode(), C->isOpaque()); 4672 case ISD::TRUNCATE: 4673 if (C->isOpaque()) 4674 break; 4675 LLVM_FALLTHROUGH; 4676 case ISD::ZERO_EXTEND: 4677 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4678 C->isTargetOpcode(), C->isOpaque()); 4679 case ISD::ANY_EXTEND: 4680 // Some targets like RISCV prefer to sign extend some types. 4681 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4682 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4683 C->isTargetOpcode(), C->isOpaque()); 4684 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4685 C->isTargetOpcode(), C->isOpaque()); 4686 case ISD::UINT_TO_FP: 4687 case ISD::SINT_TO_FP: { 4688 APFloat apf(EVTToAPFloatSemantics(VT), 4689 APInt::getNullValue(VT.getSizeInBits())); 4690 (void)apf.convertFromAPInt(Val, 4691 Opcode==ISD::SINT_TO_FP, 4692 APFloat::rmNearestTiesToEven); 4693 return getConstantFP(apf, DL, VT); 4694 } 4695 case ISD::BITCAST: 4696 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4697 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4698 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4699 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4700 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4701 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4702 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4703 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4704 break; 4705 case ISD::ABS: 4706 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4707 C->isOpaque()); 4708 case ISD::BITREVERSE: 4709 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4710 C->isOpaque()); 4711 case ISD::BSWAP: 4712 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4713 C->isOpaque()); 4714 case ISD::CTPOP: 4715 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4716 C->isOpaque()); 4717 case ISD::CTLZ: 4718 case ISD::CTLZ_ZERO_UNDEF: 4719 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4720 C->isOpaque()); 4721 case ISD::CTTZ: 4722 case ISD::CTTZ_ZERO_UNDEF: 4723 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4724 C->isOpaque()); 4725 case ISD::FP16_TO_FP: { 4726 bool Ignored; 4727 APFloat FPV(APFloat::IEEEhalf(), 4728 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4729 4730 // This can return overflow, underflow, or inexact; we don't care. 4731 // FIXME need to be more flexible about rounding mode. 4732 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4733 APFloat::rmNearestTiesToEven, &Ignored); 4734 return getConstantFP(FPV, DL, VT); 4735 } 4736 case ISD::STEP_VECTOR: { 4737 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4738 return V; 4739 break; 4740 } 4741 } 4742 } 4743 4744 // Constant fold unary operations with a floating point constant operand. 4745 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4746 APFloat V = C->getValueAPF(); // make copy 4747 switch (Opcode) { 4748 case ISD::FNEG: 4749 V.changeSign(); 4750 return getConstantFP(V, DL, VT); 4751 case ISD::FABS: 4752 V.clearSign(); 4753 return getConstantFP(V, DL, VT); 4754 case ISD::FCEIL: { 4755 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4756 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4757 return getConstantFP(V, DL, VT); 4758 break; 4759 } 4760 case ISD::FTRUNC: { 4761 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4762 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4763 return getConstantFP(V, DL, VT); 4764 break; 4765 } 4766 case ISD::FFLOOR: { 4767 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4768 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4769 return getConstantFP(V, DL, VT); 4770 break; 4771 } 4772 case ISD::FP_EXTEND: { 4773 bool ignored; 4774 // This can return overflow, underflow, or inexact; we don't care. 4775 // FIXME need to be more flexible about rounding mode. 4776 (void)V.convert(EVTToAPFloatSemantics(VT), 4777 APFloat::rmNearestTiesToEven, &ignored); 4778 return getConstantFP(V, DL, VT); 4779 } 4780 case ISD::FP_TO_SINT: 4781 case ISD::FP_TO_UINT: { 4782 bool ignored; 4783 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4784 // FIXME need to be more flexible about rounding mode. 4785 APFloat::opStatus s = 4786 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4787 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4788 break; 4789 return getConstant(IntVal, DL, VT); 4790 } 4791 case ISD::BITCAST: 4792 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4793 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4794 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4795 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4796 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4797 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4798 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4799 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4800 break; 4801 case ISD::FP_TO_FP16: { 4802 bool Ignored; 4803 // This can return overflow, underflow, or inexact; we don't care. 4804 // FIXME need to be more flexible about rounding mode. 4805 (void)V.convert(APFloat::IEEEhalf(), 4806 APFloat::rmNearestTiesToEven, &Ignored); 4807 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4808 } 4809 } 4810 } 4811 4812 // Constant fold unary operations with a vector integer or float operand. 4813 switch (Opcode) { 4814 default: 4815 // FIXME: Entirely reasonable to perform folding of other unary 4816 // operations here as the need arises. 4817 break; 4818 case ISD::FNEG: 4819 case ISD::FABS: 4820 case ISD::FCEIL: 4821 case ISD::FTRUNC: 4822 case ISD::FFLOOR: 4823 case ISD::FP_EXTEND: 4824 case ISD::FP_TO_SINT: 4825 case ISD::FP_TO_UINT: 4826 case ISD::TRUNCATE: 4827 case ISD::ANY_EXTEND: 4828 case ISD::ZERO_EXTEND: 4829 case ISD::SIGN_EXTEND: 4830 case ISD::UINT_TO_FP: 4831 case ISD::SINT_TO_FP: 4832 case ISD::ABS: 4833 case ISD::BITREVERSE: 4834 case ISD::BSWAP: 4835 case ISD::CTLZ: 4836 case ISD::CTLZ_ZERO_UNDEF: 4837 case ISD::CTTZ: 4838 case ISD::CTTZ_ZERO_UNDEF: 4839 case ISD::CTPOP: { 4840 SDValue Ops = {Operand}; 4841 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4842 return Fold; 4843 } 4844 } 4845 4846 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4847 switch (Opcode) { 4848 case ISD::STEP_VECTOR: 4849 assert(VT.isScalableVector() && 4850 "STEP_VECTOR can only be used with scalable types"); 4851 assert(OpOpcode == ISD::TargetConstant && 4852 VT.getVectorElementType() == Operand.getValueType() && 4853 "Unexpected step operand"); 4854 break; 4855 case ISD::FREEZE: 4856 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4857 break; 4858 case ISD::TokenFactor: 4859 case ISD::MERGE_VALUES: 4860 case ISD::CONCAT_VECTORS: 4861 return Operand; // Factor, merge or concat of one node? No need. 4862 case ISD::BUILD_VECTOR: { 4863 // Attempt to simplify BUILD_VECTOR. 4864 SDValue Ops[] = {Operand}; 4865 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4866 return V; 4867 break; 4868 } 4869 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4870 case ISD::FP_EXTEND: 4871 assert(VT.isFloatingPoint() && 4872 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4873 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4874 assert((!VT.isVector() || 4875 VT.getVectorElementCount() == 4876 Operand.getValueType().getVectorElementCount()) && 4877 "Vector element count mismatch!"); 4878 assert(Operand.getValueType().bitsLT(VT) && 4879 "Invalid fpext node, dst < src!"); 4880 if (Operand.isUndef()) 4881 return getUNDEF(VT); 4882 break; 4883 case ISD::FP_TO_SINT: 4884 case ISD::FP_TO_UINT: 4885 if (Operand.isUndef()) 4886 return getUNDEF(VT); 4887 break; 4888 case ISD::SINT_TO_FP: 4889 case ISD::UINT_TO_FP: 4890 // [us]itofp(undef) = 0, because the result value is bounded. 4891 if (Operand.isUndef()) 4892 return getConstantFP(0.0, DL, VT); 4893 break; 4894 case ISD::SIGN_EXTEND: 4895 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4896 "Invalid SIGN_EXTEND!"); 4897 assert(VT.isVector() == Operand.getValueType().isVector() && 4898 "SIGN_EXTEND result type type should be vector iff the operand " 4899 "type is vector!"); 4900 if (Operand.getValueType() == VT) return Operand; // noop extension 4901 assert((!VT.isVector() || 4902 VT.getVectorElementCount() == 4903 Operand.getValueType().getVectorElementCount()) && 4904 "Vector element count mismatch!"); 4905 assert(Operand.getValueType().bitsLT(VT) && 4906 "Invalid sext node, dst < src!"); 4907 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4908 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4909 if (OpOpcode == ISD::UNDEF) 4910 // sext(undef) = 0, because the top bits will all be the same. 4911 return getConstant(0, DL, VT); 4912 break; 4913 case ISD::ZERO_EXTEND: 4914 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4915 "Invalid ZERO_EXTEND!"); 4916 assert(VT.isVector() == Operand.getValueType().isVector() && 4917 "ZERO_EXTEND result type type should be vector iff the operand " 4918 "type is vector!"); 4919 if (Operand.getValueType() == VT) return Operand; // noop extension 4920 assert((!VT.isVector() || 4921 VT.getVectorElementCount() == 4922 Operand.getValueType().getVectorElementCount()) && 4923 "Vector element count mismatch!"); 4924 assert(Operand.getValueType().bitsLT(VT) && 4925 "Invalid zext node, dst < src!"); 4926 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4927 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4928 if (OpOpcode == ISD::UNDEF) 4929 // zext(undef) = 0, because the top bits will be zero. 4930 return getConstant(0, DL, VT); 4931 break; 4932 case ISD::ANY_EXTEND: 4933 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4934 "Invalid ANY_EXTEND!"); 4935 assert(VT.isVector() == Operand.getValueType().isVector() && 4936 "ANY_EXTEND result type type should be vector iff the operand " 4937 "type is vector!"); 4938 if (Operand.getValueType() == VT) return Operand; // noop extension 4939 assert((!VT.isVector() || 4940 VT.getVectorElementCount() == 4941 Operand.getValueType().getVectorElementCount()) && 4942 "Vector element count mismatch!"); 4943 assert(Operand.getValueType().bitsLT(VT) && 4944 "Invalid anyext node, dst < src!"); 4945 4946 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4947 OpOpcode == ISD::ANY_EXTEND) 4948 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4949 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4950 if (OpOpcode == ISD::UNDEF) 4951 return getUNDEF(VT); 4952 4953 // (ext (trunc x)) -> x 4954 if (OpOpcode == ISD::TRUNCATE) { 4955 SDValue OpOp = Operand.getOperand(0); 4956 if (OpOp.getValueType() == VT) { 4957 transferDbgValues(Operand, OpOp); 4958 return OpOp; 4959 } 4960 } 4961 break; 4962 case ISD::TRUNCATE: 4963 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4964 "Invalid TRUNCATE!"); 4965 assert(VT.isVector() == Operand.getValueType().isVector() && 4966 "TRUNCATE result type type should be vector iff the operand " 4967 "type is vector!"); 4968 if (Operand.getValueType() == VT) return Operand; // noop truncate 4969 assert((!VT.isVector() || 4970 VT.getVectorElementCount() == 4971 Operand.getValueType().getVectorElementCount()) && 4972 "Vector element count mismatch!"); 4973 assert(Operand.getValueType().bitsGT(VT) && 4974 "Invalid truncate node, src < dst!"); 4975 if (OpOpcode == ISD::TRUNCATE) 4976 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4977 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4978 OpOpcode == ISD::ANY_EXTEND) { 4979 // If the source is smaller than the dest, we still need an extend. 4980 if (Operand.getOperand(0).getValueType().getScalarType() 4981 .bitsLT(VT.getScalarType())) 4982 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4983 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4984 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4985 return Operand.getOperand(0); 4986 } 4987 if (OpOpcode == ISD::UNDEF) 4988 return getUNDEF(VT); 4989 break; 4990 case ISD::ANY_EXTEND_VECTOR_INREG: 4991 case ISD::ZERO_EXTEND_VECTOR_INREG: 4992 case ISD::SIGN_EXTEND_VECTOR_INREG: 4993 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4994 assert(Operand.getValueType().bitsLE(VT) && 4995 "The input must be the same size or smaller than the result."); 4996 assert(VT.getVectorMinNumElements() < 4997 Operand.getValueType().getVectorMinNumElements() && 4998 "The destination vector type must have fewer lanes than the input."); 4999 break; 5000 case ISD::ABS: 5001 assert(VT.isInteger() && VT == Operand.getValueType() && 5002 "Invalid ABS!"); 5003 if (OpOpcode == ISD::UNDEF) 5004 return getUNDEF(VT); 5005 break; 5006 case ISD::BSWAP: 5007 assert(VT.isInteger() && VT == Operand.getValueType() && 5008 "Invalid BSWAP!"); 5009 assert((VT.getScalarSizeInBits() % 16 == 0) && 5010 "BSWAP types must be a multiple of 16 bits!"); 5011 if (OpOpcode == ISD::UNDEF) 5012 return getUNDEF(VT); 5013 break; 5014 case ISD::BITREVERSE: 5015 assert(VT.isInteger() && VT == Operand.getValueType() && 5016 "Invalid BITREVERSE!"); 5017 if (OpOpcode == ISD::UNDEF) 5018 return getUNDEF(VT); 5019 break; 5020 case ISD::BITCAST: 5021 // Basic sanity checking. 5022 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5023 "Cannot BITCAST between types of different sizes!"); 5024 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5025 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5026 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5027 if (OpOpcode == ISD::UNDEF) 5028 return getUNDEF(VT); 5029 break; 5030 case ISD::SCALAR_TO_VECTOR: 5031 assert(VT.isVector() && !Operand.getValueType().isVector() && 5032 (VT.getVectorElementType() == Operand.getValueType() || 5033 (VT.getVectorElementType().isInteger() && 5034 Operand.getValueType().isInteger() && 5035 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5036 "Illegal SCALAR_TO_VECTOR node!"); 5037 if (OpOpcode == ISD::UNDEF) 5038 return getUNDEF(VT); 5039 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5040 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5041 isa<ConstantSDNode>(Operand.getOperand(1)) && 5042 Operand.getConstantOperandVal(1) == 0 && 5043 Operand.getOperand(0).getValueType() == VT) 5044 return Operand.getOperand(0); 5045 break; 5046 case ISD::FNEG: 5047 // Negation of an unknown bag of bits is still completely undefined. 5048 if (OpOpcode == ISD::UNDEF) 5049 return getUNDEF(VT); 5050 5051 if (OpOpcode == ISD::FNEG) // --X -> X 5052 return Operand.getOperand(0); 5053 break; 5054 case ISD::FABS: 5055 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5056 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5057 break; 5058 case ISD::VSCALE: 5059 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5060 break; 5061 case ISD::CTPOP: 5062 if (Operand.getValueType().getScalarType() == MVT::i1) 5063 return Operand; 5064 break; 5065 case ISD::CTLZ: 5066 case ISD::CTTZ: 5067 if (Operand.getValueType().getScalarType() == MVT::i1) 5068 return getNOT(DL, Operand, Operand.getValueType()); 5069 break; 5070 case ISD::VECREDUCE_SMIN: 5071 case ISD::VECREDUCE_UMAX: 5072 if (Operand.getValueType().getScalarType() == MVT::i1) 5073 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5074 break; 5075 case ISD::VECREDUCE_SMAX: 5076 case ISD::VECREDUCE_UMIN: 5077 if (Operand.getValueType().getScalarType() == MVT::i1) 5078 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5079 break; 5080 } 5081 5082 SDNode *N; 5083 SDVTList VTs = getVTList(VT); 5084 SDValue Ops[] = {Operand}; 5085 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5086 FoldingSetNodeID ID; 5087 AddNodeIDNode(ID, Opcode, VTs, Ops); 5088 void *IP = nullptr; 5089 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5090 E->intersectFlagsWith(Flags); 5091 return SDValue(E, 0); 5092 } 5093 5094 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5095 N->setFlags(Flags); 5096 createOperands(N, Ops); 5097 CSEMap.InsertNode(N, IP); 5098 } else { 5099 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5100 createOperands(N, Ops); 5101 } 5102 5103 InsertNode(N); 5104 SDValue V = SDValue(N, 0); 5105 NewSDValueDbgMsg(V, "Creating new node: ", this); 5106 return V; 5107 } 5108 5109 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5110 const APInt &C2) { 5111 switch (Opcode) { 5112 case ISD::ADD: return C1 + C2; 5113 case ISD::SUB: return C1 - C2; 5114 case ISD::MUL: return C1 * C2; 5115 case ISD::AND: return C1 & C2; 5116 case ISD::OR: return C1 | C2; 5117 case ISD::XOR: return C1 ^ C2; 5118 case ISD::SHL: return C1 << C2; 5119 case ISD::SRL: return C1.lshr(C2); 5120 case ISD::SRA: return C1.ashr(C2); 5121 case ISD::ROTL: return C1.rotl(C2); 5122 case ISD::ROTR: return C1.rotr(C2); 5123 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5124 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5125 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5126 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5127 case ISD::SADDSAT: return C1.sadd_sat(C2); 5128 case ISD::UADDSAT: return C1.uadd_sat(C2); 5129 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5130 case ISD::USUBSAT: return C1.usub_sat(C2); 5131 case ISD::UDIV: 5132 if (!C2.getBoolValue()) 5133 break; 5134 return C1.udiv(C2); 5135 case ISD::UREM: 5136 if (!C2.getBoolValue()) 5137 break; 5138 return C1.urem(C2); 5139 case ISD::SDIV: 5140 if (!C2.getBoolValue()) 5141 break; 5142 return C1.sdiv(C2); 5143 case ISD::SREM: 5144 if (!C2.getBoolValue()) 5145 break; 5146 return C1.srem(C2); 5147 case ISD::MULHS: { 5148 unsigned FullWidth = C1.getBitWidth() * 2; 5149 APInt C1Ext = C1.sext(FullWidth); 5150 APInt C2Ext = C2.sext(FullWidth); 5151 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5152 } 5153 case ISD::MULHU: { 5154 unsigned FullWidth = C1.getBitWidth() * 2; 5155 APInt C1Ext = C1.zext(FullWidth); 5156 APInt C2Ext = C2.zext(FullWidth); 5157 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5158 } 5159 } 5160 return llvm::None; 5161 } 5162 5163 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5164 const GlobalAddressSDNode *GA, 5165 const SDNode *N2) { 5166 if (GA->getOpcode() != ISD::GlobalAddress) 5167 return SDValue(); 5168 if (!TLI->isOffsetFoldingLegal(GA)) 5169 return SDValue(); 5170 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5171 if (!C2) 5172 return SDValue(); 5173 int64_t Offset = C2->getSExtValue(); 5174 switch (Opcode) { 5175 case ISD::ADD: break; 5176 case ISD::SUB: Offset = -uint64_t(Offset); break; 5177 default: return SDValue(); 5178 } 5179 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5180 GA->getOffset() + uint64_t(Offset)); 5181 } 5182 5183 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5184 switch (Opcode) { 5185 case ISD::SDIV: 5186 case ISD::UDIV: 5187 case ISD::SREM: 5188 case ISD::UREM: { 5189 // If a divisor is zero/undef or any element of a divisor vector is 5190 // zero/undef, the whole op is undef. 5191 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5192 SDValue Divisor = Ops[1]; 5193 if (Divisor.isUndef() || isNullConstant(Divisor)) 5194 return true; 5195 5196 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5197 llvm::any_of(Divisor->op_values(), 5198 [](SDValue V) { return V.isUndef() || 5199 isNullConstant(V); }); 5200 // TODO: Handle signed overflow. 5201 } 5202 // TODO: Handle oversized shifts. 5203 default: 5204 return false; 5205 } 5206 } 5207 5208 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5209 EVT VT, ArrayRef<SDValue> Ops) { 5210 // If the opcode is a target-specific ISD node, there's nothing we can 5211 // do here and the operand rules may not line up with the below, so 5212 // bail early. 5213 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5214 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5215 // foldCONCAT_VECTORS in getNode before this is called. 5216 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5217 return SDValue(); 5218 5219 // For now, the array Ops should only contain two values. 5220 // This enforcement will be removed once this function is merged with 5221 // FoldConstantVectorArithmetic 5222 if (Ops.size() != 2) 5223 return SDValue(); 5224 5225 if (isUndef(Opcode, Ops)) 5226 return getUNDEF(VT); 5227 5228 SDNode *N1 = Ops[0].getNode(); 5229 SDNode *N2 = Ops[1].getNode(); 5230 5231 // Handle the case of two scalars. 5232 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 5233 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 5234 if (C1->isOpaque() || C2->isOpaque()) 5235 return SDValue(); 5236 5237 Optional<APInt> FoldAttempt = 5238 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5239 if (!FoldAttempt) 5240 return SDValue(); 5241 5242 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5243 assert((!Folded || !VT.isVector()) && 5244 "Can't fold vectors ops with scalar operands"); 5245 return Folded; 5246 } 5247 } 5248 5249 // fold (add Sym, c) -> Sym+c 5250 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 5251 return FoldSymbolOffset(Opcode, VT, GA, N2); 5252 if (TLI->isCommutativeBinOp(Opcode)) 5253 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 5254 return FoldSymbolOffset(Opcode, VT, GA, N1); 5255 5256 // For fixed width vectors, extract each constant element and fold them 5257 // individually. Either input may be an undef value. 5258 bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR || 5259 N1->getOpcode() == ISD::SPLAT_VECTOR; 5260 if (!IsBVOrSV1 && !N1->isUndef()) 5261 return SDValue(); 5262 bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR || 5263 N2->getOpcode() == ISD::SPLAT_VECTOR; 5264 if (!IsBVOrSV2 && !N2->isUndef()) 5265 return SDValue(); 5266 // If both operands are undef, that's handled the same way as scalars. 5267 if (!IsBVOrSV1 && !IsBVOrSV2) 5268 return SDValue(); 5269 5270 EVT SVT = VT.getScalarType(); 5271 EVT LegalSVT = SVT; 5272 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5273 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5274 if (LegalSVT.bitsLT(SVT)) 5275 return SDValue(); 5276 } 5277 5278 SmallVector<SDValue, 4> Outputs; 5279 unsigned NumOps = 0; 5280 if (IsBVOrSV1) 5281 NumOps = std::max(NumOps, N1->getNumOperands()); 5282 if (IsBVOrSV2) 5283 NumOps = std::max(NumOps, N2->getNumOperands()); 5284 assert(NumOps != 0 && "Expected non-zero operands"); 5285 // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need 5286 // one iteration for that. 5287 assert((!VT.isScalableVector() || NumOps == 1) && 5288 "Scalable vector should only have one scalar"); 5289 5290 for (unsigned I = 0; I != NumOps; ++I) { 5291 // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need 5292 // to use operand 0 of the SPLAT_VECTOR for each fixed element. 5293 SDValue V1; 5294 if (N1->getOpcode() == ISD::BUILD_VECTOR) 5295 V1 = N1->getOperand(I); 5296 else if (N1->getOpcode() == ISD::SPLAT_VECTOR) 5297 V1 = N1->getOperand(0); 5298 else 5299 V1 = getUNDEF(SVT); 5300 5301 SDValue V2; 5302 if (N2->getOpcode() == ISD::BUILD_VECTOR) 5303 V2 = N2->getOperand(I); 5304 else if (N2->getOpcode() == ISD::SPLAT_VECTOR) 5305 V2 = N2->getOperand(0); 5306 else 5307 V2 = getUNDEF(SVT); 5308 5309 if (SVT.isInteger()) { 5310 if (V1.getValueType().bitsGT(SVT)) 5311 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5312 if (V2.getValueType().bitsGT(SVT)) 5313 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5314 } 5315 5316 if (V1.getValueType() != SVT || V2.getValueType() != SVT) 5317 return SDValue(); 5318 5319 // Fold one vector element. 5320 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5321 if (LegalSVT != SVT) 5322 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5323 5324 // Scalar folding only succeeded if the result is a constant or UNDEF. 5325 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5326 ScalarResult.getOpcode() != ISD::ConstantFP) 5327 return SDValue(); 5328 Outputs.push_back(ScalarResult); 5329 } 5330 5331 if (N1->getOpcode() == ISD::BUILD_VECTOR || 5332 N2->getOpcode() == ISD::BUILD_VECTOR) { 5333 assert(VT.getVectorNumElements() == Outputs.size() && 5334 "Vector size mismatch!"); 5335 5336 // Build a big vector out of the scalar elements we generated. 5337 return getBuildVector(VT, SDLoc(), Outputs); 5338 } 5339 5340 assert((N1->getOpcode() == ISD::SPLAT_VECTOR || 5341 N2->getOpcode() == ISD::SPLAT_VECTOR) && 5342 "One operand should be a splat vector"); 5343 5344 assert(Outputs.size() == 1 && "Vector size mismatch!"); 5345 return getSplatVector(VT, SDLoc(), Outputs[0]); 5346 } 5347 5348 // TODO: Merge with FoldConstantArithmetic 5349 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5350 const SDLoc &DL, EVT VT, 5351 ArrayRef<SDValue> Ops, 5352 const SDNodeFlags Flags) { 5353 // If the opcode is a target-specific ISD node, there's nothing we can 5354 // do here and the operand rules may not line up with the below, so 5355 // bail early. 5356 if (Opcode >= ISD::BUILTIN_OP_END) 5357 return SDValue(); 5358 5359 if (isUndef(Opcode, Ops)) 5360 return getUNDEF(VT); 5361 5362 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5363 if (!VT.isVector()) 5364 return SDValue(); 5365 5366 ElementCount NumElts = VT.getVectorElementCount(); 5367 5368 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5369 return !Op.getValueType().isVector() || 5370 Op.getValueType().getVectorElementCount() == NumElts; 5371 }; 5372 5373 auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5374 APInt SplatVal; 5375 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5376 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5377 (BV && BV->isConstant()) || 5378 (Op.getOpcode() == ISD::SPLAT_VECTOR && 5379 ISD::isConstantSplatVector(Op.getNode(), SplatVal)); 5380 }; 5381 5382 // All operands must be vector types with the same number of elements as 5383 // the result type and must be either UNDEF or a build vector of constant 5384 // or UNDEF scalars. 5385 if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) || 5386 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5387 return SDValue(); 5388 5389 // If we are comparing vectors, then the result needs to be a i1 boolean 5390 // that is then sign-extended back to the legal result type. 5391 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5392 5393 // Find legal integer scalar type for constant promotion and 5394 // ensure that its scalar size is at least as large as source. 5395 EVT LegalSVT = VT.getScalarType(); 5396 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5397 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5398 if (LegalSVT.bitsLT(VT.getScalarType())) 5399 return SDValue(); 5400 } 5401 5402 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5403 // only have one operand to check. For fixed-length vector types we may have 5404 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5405 unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5406 5407 // Constant fold each scalar lane separately. 5408 SmallVector<SDValue, 4> ScalarResults; 5409 for (unsigned I = 0; I != NumOperands; I++) { 5410 SmallVector<SDValue, 4> ScalarOps; 5411 for (SDValue Op : Ops) { 5412 EVT InSVT = Op.getValueType().getScalarType(); 5413 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5414 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5415 // We've checked that this is UNDEF or a constant of some kind. 5416 if (Op.isUndef()) 5417 ScalarOps.push_back(getUNDEF(InSVT)); 5418 else 5419 ScalarOps.push_back(Op); 5420 continue; 5421 } 5422 5423 SDValue ScalarOp = 5424 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5425 EVT ScalarVT = ScalarOp.getValueType(); 5426 5427 // Build vector (integer) scalar operands may need implicit 5428 // truncation - do this before constant folding. 5429 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5430 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5431 5432 ScalarOps.push_back(ScalarOp); 5433 } 5434 5435 // Constant fold the scalar operands. 5436 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5437 5438 // Legalize the (integer) scalar constant if necessary. 5439 if (LegalSVT != SVT) 5440 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5441 5442 // Scalar folding only succeeded if the result is a constant or UNDEF. 5443 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5444 ScalarResult.getOpcode() != ISD::ConstantFP) 5445 return SDValue(); 5446 ScalarResults.push_back(ScalarResult); 5447 } 5448 5449 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5450 : getBuildVector(VT, DL, ScalarResults); 5451 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5452 return V; 5453 } 5454 5455 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5456 EVT VT, SDValue N1, SDValue N2) { 5457 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5458 // should. That will require dealing with a potentially non-default 5459 // rounding mode, checking the "opStatus" return value from the APFloat 5460 // math calculations, and possibly other variations. 5461 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5462 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5463 if (N1CFP && N2CFP) { 5464 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5465 switch (Opcode) { 5466 case ISD::FADD: 5467 C1.add(C2, APFloat::rmNearestTiesToEven); 5468 return getConstantFP(C1, DL, VT); 5469 case ISD::FSUB: 5470 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5471 return getConstantFP(C1, DL, VT); 5472 case ISD::FMUL: 5473 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5474 return getConstantFP(C1, DL, VT); 5475 case ISD::FDIV: 5476 C1.divide(C2, APFloat::rmNearestTiesToEven); 5477 return getConstantFP(C1, DL, VT); 5478 case ISD::FREM: 5479 C1.mod(C2); 5480 return getConstantFP(C1, DL, VT); 5481 case ISD::FCOPYSIGN: 5482 C1.copySign(C2); 5483 return getConstantFP(C1, DL, VT); 5484 default: break; 5485 } 5486 } 5487 if (N1CFP && Opcode == ISD::FP_ROUND) { 5488 APFloat C1 = N1CFP->getValueAPF(); // make copy 5489 bool Unused; 5490 // This can return overflow, underflow, or inexact; we don't care. 5491 // FIXME need to be more flexible about rounding mode. 5492 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5493 &Unused); 5494 return getConstantFP(C1, DL, VT); 5495 } 5496 5497 switch (Opcode) { 5498 case ISD::FSUB: 5499 // -0.0 - undef --> undef (consistent with "fneg undef") 5500 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5501 return getUNDEF(VT); 5502 LLVM_FALLTHROUGH; 5503 5504 case ISD::FADD: 5505 case ISD::FMUL: 5506 case ISD::FDIV: 5507 case ISD::FREM: 5508 // If both operands are undef, the result is undef. If 1 operand is undef, 5509 // the result is NaN. This should match the behavior of the IR optimizer. 5510 if (N1.isUndef() && N2.isUndef()) 5511 return getUNDEF(VT); 5512 if (N1.isUndef() || N2.isUndef()) 5513 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5514 } 5515 return SDValue(); 5516 } 5517 5518 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5519 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5520 5521 // There's no need to assert on a byte-aligned pointer. All pointers are at 5522 // least byte aligned. 5523 if (A == Align(1)) 5524 return Val; 5525 5526 FoldingSetNodeID ID; 5527 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5528 ID.AddInteger(A.value()); 5529 5530 void *IP = nullptr; 5531 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5532 return SDValue(E, 0); 5533 5534 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5535 Val.getValueType(), A); 5536 createOperands(N, {Val}); 5537 5538 CSEMap.InsertNode(N, IP); 5539 InsertNode(N); 5540 5541 SDValue V(N, 0); 5542 NewSDValueDbgMsg(V, "Creating new node: ", this); 5543 return V; 5544 } 5545 5546 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5547 SDValue N1, SDValue N2) { 5548 SDNodeFlags Flags; 5549 if (Inserter) 5550 Flags = Inserter->getFlags(); 5551 return getNode(Opcode, DL, VT, N1, N2, Flags); 5552 } 5553 5554 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5555 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5556 assert(N1.getOpcode() != ISD::DELETED_NODE && 5557 N2.getOpcode() != ISD::DELETED_NODE && 5558 "Operand is DELETED_NODE!"); 5559 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5560 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5561 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5562 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5563 5564 // Canonicalize constant to RHS if commutative. 5565 if (TLI->isCommutativeBinOp(Opcode)) { 5566 if (N1C && !N2C) { 5567 std::swap(N1C, N2C); 5568 std::swap(N1, N2); 5569 } else if (N1CFP && !N2CFP) { 5570 std::swap(N1CFP, N2CFP); 5571 std::swap(N1, N2); 5572 } 5573 } 5574 5575 switch (Opcode) { 5576 default: break; 5577 case ISD::TokenFactor: 5578 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5579 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5580 // Fold trivial token factors. 5581 if (N1.getOpcode() == ISD::EntryToken) return N2; 5582 if (N2.getOpcode() == ISD::EntryToken) return N1; 5583 if (N1 == N2) return N1; 5584 break; 5585 case ISD::BUILD_VECTOR: { 5586 // Attempt to simplify BUILD_VECTOR. 5587 SDValue Ops[] = {N1, N2}; 5588 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5589 return V; 5590 break; 5591 } 5592 case ISD::CONCAT_VECTORS: { 5593 SDValue Ops[] = {N1, N2}; 5594 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5595 return V; 5596 break; 5597 } 5598 case ISD::AND: 5599 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5600 assert(N1.getValueType() == N2.getValueType() && 5601 N1.getValueType() == VT && "Binary operator types must match!"); 5602 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5603 // worth handling here. 5604 if (N2C && N2C->isNullValue()) 5605 return N2; 5606 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5607 return N1; 5608 break; 5609 case ISD::OR: 5610 case ISD::XOR: 5611 case ISD::ADD: 5612 case ISD::SUB: 5613 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5614 assert(N1.getValueType() == N2.getValueType() && 5615 N1.getValueType() == VT && "Binary operator types must match!"); 5616 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5617 // it's worth handling here. 5618 if (N2C && N2C->isNullValue()) 5619 return N1; 5620 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5621 VT.getVectorElementType() == MVT::i1) 5622 return getNode(ISD::XOR, DL, VT, N1, N2); 5623 break; 5624 case ISD::MUL: 5625 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5626 assert(N1.getValueType() == N2.getValueType() && 5627 N1.getValueType() == VT && "Binary operator types must match!"); 5628 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5629 return getNode(ISD::AND, DL, VT, N1, N2); 5630 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5631 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5632 const APInt &N2CImm = N2C->getAPIntValue(); 5633 return getVScale(DL, VT, MulImm * N2CImm); 5634 } 5635 break; 5636 case ISD::UDIV: 5637 case ISD::UREM: 5638 case ISD::MULHU: 5639 case ISD::MULHS: 5640 case ISD::SDIV: 5641 case ISD::SREM: 5642 case ISD::SADDSAT: 5643 case ISD::SSUBSAT: 5644 case ISD::UADDSAT: 5645 case ISD::USUBSAT: 5646 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5647 assert(N1.getValueType() == N2.getValueType() && 5648 N1.getValueType() == VT && "Binary operator types must match!"); 5649 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5650 // fold (add_sat x, y) -> (or x, y) for bool types. 5651 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5652 return getNode(ISD::OR, DL, VT, N1, N2); 5653 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5654 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5655 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5656 } 5657 break; 5658 case ISD::SMIN: 5659 case ISD::UMAX: 5660 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5661 assert(N1.getValueType() == N2.getValueType() && 5662 N1.getValueType() == VT && "Binary operator types must match!"); 5663 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5664 return getNode(ISD::OR, DL, VT, N1, N2); 5665 break; 5666 case ISD::SMAX: 5667 case ISD::UMIN: 5668 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5669 assert(N1.getValueType() == N2.getValueType() && 5670 N1.getValueType() == VT && "Binary operator types must match!"); 5671 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5672 return getNode(ISD::AND, DL, VT, N1, N2); 5673 break; 5674 case ISD::FADD: 5675 case ISD::FSUB: 5676 case ISD::FMUL: 5677 case ISD::FDIV: 5678 case ISD::FREM: 5679 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5680 assert(N1.getValueType() == N2.getValueType() && 5681 N1.getValueType() == VT && "Binary operator types must match!"); 5682 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5683 return V; 5684 break; 5685 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5686 assert(N1.getValueType() == VT && 5687 N1.getValueType().isFloatingPoint() && 5688 N2.getValueType().isFloatingPoint() && 5689 "Invalid FCOPYSIGN!"); 5690 break; 5691 case ISD::SHL: 5692 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5693 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5694 const APInt &ShiftImm = N2C->getAPIntValue(); 5695 return getVScale(DL, VT, MulImm << ShiftImm); 5696 } 5697 LLVM_FALLTHROUGH; 5698 case ISD::SRA: 5699 case ISD::SRL: 5700 if (SDValue V = simplifyShift(N1, N2)) 5701 return V; 5702 LLVM_FALLTHROUGH; 5703 case ISD::ROTL: 5704 case ISD::ROTR: 5705 assert(VT == N1.getValueType() && 5706 "Shift operators return type must be the same as their first arg"); 5707 assert(VT.isInteger() && N2.getValueType().isInteger() && 5708 "Shifts only work on integers"); 5709 assert((!VT.isVector() || VT == N2.getValueType()) && 5710 "Vector shift amounts must be in the same as their first arg"); 5711 // Verify that the shift amount VT is big enough to hold valid shift 5712 // amounts. This catches things like trying to shift an i1024 value by an 5713 // i8, which is easy to fall into in generic code that uses 5714 // TLI.getShiftAmount(). 5715 assert(N2.getValueType().getScalarSizeInBits() >= 5716 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5717 "Invalid use of small shift amount with oversized value!"); 5718 5719 // Always fold shifts of i1 values so the code generator doesn't need to 5720 // handle them. Since we know the size of the shift has to be less than the 5721 // size of the value, the shift/rotate count is guaranteed to be zero. 5722 if (VT == MVT::i1) 5723 return N1; 5724 if (N2C && N2C->isNullValue()) 5725 return N1; 5726 break; 5727 case ISD::FP_ROUND: 5728 assert(VT.isFloatingPoint() && 5729 N1.getValueType().isFloatingPoint() && 5730 VT.bitsLE(N1.getValueType()) && 5731 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5732 "Invalid FP_ROUND!"); 5733 if (N1.getValueType() == VT) return N1; // noop conversion. 5734 break; 5735 case ISD::AssertSext: 5736 case ISD::AssertZext: { 5737 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5738 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5739 assert(VT.isInteger() && EVT.isInteger() && 5740 "Cannot *_EXTEND_INREG FP types"); 5741 assert(!EVT.isVector() && 5742 "AssertSExt/AssertZExt type should be the vector element type " 5743 "rather than the vector type!"); 5744 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5745 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5746 break; 5747 } 5748 case ISD::SIGN_EXTEND_INREG: { 5749 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5750 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5751 assert(VT.isInteger() && EVT.isInteger() && 5752 "Cannot *_EXTEND_INREG FP types"); 5753 assert(EVT.isVector() == VT.isVector() && 5754 "SIGN_EXTEND_INREG type should be vector iff the operand " 5755 "type is vector!"); 5756 assert((!EVT.isVector() || 5757 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5758 "Vector element counts must match in SIGN_EXTEND_INREG"); 5759 assert(EVT.bitsLE(VT) && "Not extending!"); 5760 if (EVT == VT) return N1; // Not actually extending 5761 5762 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5763 unsigned FromBits = EVT.getScalarSizeInBits(); 5764 Val <<= Val.getBitWidth() - FromBits; 5765 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5766 return getConstant(Val, DL, ConstantVT); 5767 }; 5768 5769 if (N1C) { 5770 const APInt &Val = N1C->getAPIntValue(); 5771 return SignExtendInReg(Val, VT); 5772 } 5773 5774 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5775 SmallVector<SDValue, 8> Ops; 5776 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5777 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5778 SDValue Op = N1.getOperand(i); 5779 if (Op.isUndef()) { 5780 Ops.push_back(getUNDEF(OpVT)); 5781 continue; 5782 } 5783 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5784 APInt Val = C->getAPIntValue(); 5785 Ops.push_back(SignExtendInReg(Val, OpVT)); 5786 } 5787 return getBuildVector(VT, DL, Ops); 5788 } 5789 break; 5790 } 5791 case ISD::FP_TO_SINT_SAT: 5792 case ISD::FP_TO_UINT_SAT: { 5793 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5794 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5795 assert(N1.getValueType().isVector() == VT.isVector() && 5796 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5797 "vector!"); 5798 assert((!VT.isVector() || VT.getVectorNumElements() == 5799 N1.getValueType().getVectorNumElements()) && 5800 "Vector element counts must match in FP_TO_*INT_SAT"); 5801 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5802 "Type to saturate to must be a scalar."); 5803 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5804 "Not extending!"); 5805 break; 5806 } 5807 case ISD::EXTRACT_VECTOR_ELT: 5808 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5809 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5810 element type of the vector."); 5811 5812 // Extract from an undefined value or using an undefined index is undefined. 5813 if (N1.isUndef() || N2.isUndef()) 5814 return getUNDEF(VT); 5815 5816 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5817 // vectors. For scalable vectors we will provide appropriate support for 5818 // dealing with arbitrary indices. 5819 if (N2C && N1.getValueType().isFixedLengthVector() && 5820 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5821 return getUNDEF(VT); 5822 5823 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5824 // expanding copies of large vectors from registers. This only works for 5825 // fixed length vectors, since we need to know the exact number of 5826 // elements. 5827 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5828 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5829 unsigned Factor = 5830 N1.getOperand(0).getValueType().getVectorNumElements(); 5831 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5832 N1.getOperand(N2C->getZExtValue() / Factor), 5833 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5834 } 5835 5836 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5837 // lowering is expanding large vector constants. 5838 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5839 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5840 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5841 N1.getValueType().isFixedLengthVector()) && 5842 "BUILD_VECTOR used for scalable vectors"); 5843 unsigned Index = 5844 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5845 SDValue Elt = N1.getOperand(Index); 5846 5847 if (VT != Elt.getValueType()) 5848 // If the vector element type is not legal, the BUILD_VECTOR operands 5849 // are promoted and implicitly truncated, and the result implicitly 5850 // extended. Make that explicit here. 5851 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5852 5853 return Elt; 5854 } 5855 5856 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5857 // operations are lowered to scalars. 5858 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5859 // If the indices are the same, return the inserted element else 5860 // if the indices are known different, extract the element from 5861 // the original vector. 5862 SDValue N1Op2 = N1.getOperand(2); 5863 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5864 5865 if (N1Op2C && N2C) { 5866 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5867 if (VT == N1.getOperand(1).getValueType()) 5868 return N1.getOperand(1); 5869 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5870 } 5871 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5872 } 5873 } 5874 5875 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5876 // when vector types are scalarized and v1iX is legal. 5877 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5878 // Here we are completely ignoring the extract element index (N2), 5879 // which is fine for fixed width vectors, since any index other than 0 5880 // is undefined anyway. However, this cannot be ignored for scalable 5881 // vectors - in theory we could support this, but we don't want to do this 5882 // without a profitability check. 5883 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5884 N1.getValueType().isFixedLengthVector() && 5885 N1.getValueType().getVectorNumElements() == 1) { 5886 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5887 N1.getOperand(1)); 5888 } 5889 break; 5890 case ISD::EXTRACT_ELEMENT: 5891 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5892 assert(!N1.getValueType().isVector() && !VT.isVector() && 5893 (N1.getValueType().isInteger() == VT.isInteger()) && 5894 N1.getValueType() != VT && 5895 "Wrong types for EXTRACT_ELEMENT!"); 5896 5897 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5898 // 64-bit integers into 32-bit parts. Instead of building the extract of 5899 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5900 if (N1.getOpcode() == ISD::BUILD_PAIR) 5901 return N1.getOperand(N2C->getZExtValue()); 5902 5903 // EXTRACT_ELEMENT of a constant int is also very common. 5904 if (N1C) { 5905 unsigned ElementSize = VT.getSizeInBits(); 5906 unsigned Shift = ElementSize * N2C->getZExtValue(); 5907 const APInt &Val = N1C->getAPIntValue(); 5908 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5909 } 5910 break; 5911 case ISD::EXTRACT_SUBVECTOR: { 5912 EVT N1VT = N1.getValueType(); 5913 assert(VT.isVector() && N1VT.isVector() && 5914 "Extract subvector VTs must be vectors!"); 5915 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5916 "Extract subvector VTs must have the same element type!"); 5917 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5918 "Cannot extract a scalable vector from a fixed length vector!"); 5919 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5920 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5921 "Extract subvector must be from larger vector to smaller vector!"); 5922 assert(N2C && "Extract subvector index must be a constant"); 5923 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5924 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5925 N1VT.getVectorMinNumElements()) && 5926 "Extract subvector overflow!"); 5927 assert(N2C->getAPIntValue().getBitWidth() == 5928 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5929 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5930 5931 // Trivial extraction. 5932 if (VT == N1VT) 5933 return N1; 5934 5935 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5936 if (N1.isUndef()) 5937 return getUNDEF(VT); 5938 5939 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5940 // the concat have the same type as the extract. 5941 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5942 VT == N1.getOperand(0).getValueType()) { 5943 unsigned Factor = VT.getVectorMinNumElements(); 5944 return N1.getOperand(N2C->getZExtValue() / Factor); 5945 } 5946 5947 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5948 // during shuffle legalization. 5949 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5950 VT == N1.getOperand(1).getValueType()) 5951 return N1.getOperand(1); 5952 break; 5953 } 5954 } 5955 5956 // Perform trivial constant folding. 5957 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5958 return SV; 5959 5960 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5961 return V; 5962 5963 // Canonicalize an UNDEF to the RHS, even over a constant. 5964 if (N1.isUndef()) { 5965 if (TLI->isCommutativeBinOp(Opcode)) { 5966 std::swap(N1, N2); 5967 } else { 5968 switch (Opcode) { 5969 case ISD::SIGN_EXTEND_INREG: 5970 case ISD::SUB: 5971 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5972 case ISD::UDIV: 5973 case ISD::SDIV: 5974 case ISD::UREM: 5975 case ISD::SREM: 5976 case ISD::SSUBSAT: 5977 case ISD::USUBSAT: 5978 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5979 } 5980 } 5981 } 5982 5983 // Fold a bunch of operators when the RHS is undef. 5984 if (N2.isUndef()) { 5985 switch (Opcode) { 5986 case ISD::XOR: 5987 if (N1.isUndef()) 5988 // Handle undef ^ undef -> 0 special case. This is a common 5989 // idiom (misuse). 5990 return getConstant(0, DL, VT); 5991 LLVM_FALLTHROUGH; 5992 case ISD::ADD: 5993 case ISD::SUB: 5994 case ISD::UDIV: 5995 case ISD::SDIV: 5996 case ISD::UREM: 5997 case ISD::SREM: 5998 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5999 case ISD::MUL: 6000 case ISD::AND: 6001 case ISD::SSUBSAT: 6002 case ISD::USUBSAT: 6003 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6004 case ISD::OR: 6005 case ISD::SADDSAT: 6006 case ISD::UADDSAT: 6007 return getAllOnesConstant(DL, VT); 6008 } 6009 } 6010 6011 // Memoize this node if possible. 6012 SDNode *N; 6013 SDVTList VTs = getVTList(VT); 6014 SDValue Ops[] = {N1, N2}; 6015 if (VT != MVT::Glue) { 6016 FoldingSetNodeID ID; 6017 AddNodeIDNode(ID, Opcode, VTs, Ops); 6018 void *IP = nullptr; 6019 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6020 E->intersectFlagsWith(Flags); 6021 return SDValue(E, 0); 6022 } 6023 6024 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6025 N->setFlags(Flags); 6026 createOperands(N, Ops); 6027 CSEMap.InsertNode(N, IP); 6028 } else { 6029 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6030 createOperands(N, Ops); 6031 } 6032 6033 InsertNode(N); 6034 SDValue V = SDValue(N, 0); 6035 NewSDValueDbgMsg(V, "Creating new node: ", this); 6036 return V; 6037 } 6038 6039 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6040 SDValue N1, SDValue N2, SDValue N3) { 6041 SDNodeFlags Flags; 6042 if (Inserter) 6043 Flags = Inserter->getFlags(); 6044 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6045 } 6046 6047 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6048 SDValue N1, SDValue N2, SDValue N3, 6049 const SDNodeFlags Flags) { 6050 assert(N1.getOpcode() != ISD::DELETED_NODE && 6051 N2.getOpcode() != ISD::DELETED_NODE && 6052 N3.getOpcode() != ISD::DELETED_NODE && 6053 "Operand is DELETED_NODE!"); 6054 // Perform various simplifications. 6055 switch (Opcode) { 6056 case ISD::FMA: { 6057 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6058 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6059 N3.getValueType() == VT && "FMA types must match!"); 6060 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6061 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6062 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6063 if (N1CFP && N2CFP && N3CFP) { 6064 APFloat V1 = N1CFP->getValueAPF(); 6065 const APFloat &V2 = N2CFP->getValueAPF(); 6066 const APFloat &V3 = N3CFP->getValueAPF(); 6067 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6068 return getConstantFP(V1, DL, VT); 6069 } 6070 break; 6071 } 6072 case ISD::BUILD_VECTOR: { 6073 // Attempt to simplify BUILD_VECTOR. 6074 SDValue Ops[] = {N1, N2, N3}; 6075 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6076 return V; 6077 break; 6078 } 6079 case ISD::CONCAT_VECTORS: { 6080 SDValue Ops[] = {N1, N2, N3}; 6081 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6082 return V; 6083 break; 6084 } 6085 case ISD::SETCC: { 6086 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6087 assert(N1.getValueType() == N2.getValueType() && 6088 "SETCC operands must have the same type!"); 6089 assert(VT.isVector() == N1.getValueType().isVector() && 6090 "SETCC type should be vector iff the operand type is vector!"); 6091 assert((!VT.isVector() || VT.getVectorElementCount() == 6092 N1.getValueType().getVectorElementCount()) && 6093 "SETCC vector element counts must match!"); 6094 // Use FoldSetCC to simplify SETCC's. 6095 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6096 return V; 6097 // Vector constant folding. 6098 SDValue Ops[] = {N1, N2, N3}; 6099 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 6100 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6101 return V; 6102 } 6103 break; 6104 } 6105 case ISD::SELECT: 6106 case ISD::VSELECT: 6107 if (SDValue V = simplifySelect(N1, N2, N3)) 6108 return V; 6109 break; 6110 case ISD::VECTOR_SHUFFLE: 6111 llvm_unreachable("should use getVectorShuffle constructor!"); 6112 case ISD::INSERT_VECTOR_ELT: { 6113 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6114 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6115 // for scalable vectors where we will generate appropriate code to 6116 // deal with out-of-bounds cases correctly. 6117 if (N3C && N1.getValueType().isFixedLengthVector() && 6118 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6119 return getUNDEF(VT); 6120 6121 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6122 if (N3.isUndef()) 6123 return getUNDEF(VT); 6124 6125 // If the inserted element is an UNDEF, just use the input vector. 6126 if (N2.isUndef()) 6127 return N1; 6128 6129 break; 6130 } 6131 case ISD::INSERT_SUBVECTOR: { 6132 // Inserting undef into undef is still undef. 6133 if (N1.isUndef() && N2.isUndef()) 6134 return getUNDEF(VT); 6135 6136 EVT N2VT = N2.getValueType(); 6137 assert(VT == N1.getValueType() && 6138 "Dest and insert subvector source types must match!"); 6139 assert(VT.isVector() && N2VT.isVector() && 6140 "Insert subvector VTs must be vectors!"); 6141 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6142 "Cannot insert a scalable vector into a fixed length vector!"); 6143 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6144 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6145 "Insert subvector must be from smaller vector to larger vector!"); 6146 assert(isa<ConstantSDNode>(N3) && 6147 "Insert subvector index must be constant"); 6148 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6149 (N2VT.getVectorMinNumElements() + 6150 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6151 VT.getVectorMinNumElements()) && 6152 "Insert subvector overflow!"); 6153 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6154 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6155 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6156 6157 // Trivial insertion. 6158 if (VT == N2VT) 6159 return N2; 6160 6161 // If this is an insert of an extracted vector into an undef vector, we 6162 // can just use the input to the extract. 6163 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6164 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6165 return N2.getOperand(0); 6166 break; 6167 } 6168 case ISD::BITCAST: 6169 // Fold bit_convert nodes from a type to themselves. 6170 if (N1.getValueType() == VT) 6171 return N1; 6172 break; 6173 } 6174 6175 // Memoize node if it doesn't produce a flag. 6176 SDNode *N; 6177 SDVTList VTs = getVTList(VT); 6178 SDValue Ops[] = {N1, N2, N3}; 6179 if (VT != MVT::Glue) { 6180 FoldingSetNodeID ID; 6181 AddNodeIDNode(ID, Opcode, VTs, Ops); 6182 void *IP = nullptr; 6183 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6184 E->intersectFlagsWith(Flags); 6185 return SDValue(E, 0); 6186 } 6187 6188 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6189 N->setFlags(Flags); 6190 createOperands(N, Ops); 6191 CSEMap.InsertNode(N, IP); 6192 } else { 6193 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6194 createOperands(N, Ops); 6195 } 6196 6197 InsertNode(N); 6198 SDValue V = SDValue(N, 0); 6199 NewSDValueDbgMsg(V, "Creating new node: ", this); 6200 return V; 6201 } 6202 6203 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6204 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6205 SDValue Ops[] = { N1, N2, N3, N4 }; 6206 return getNode(Opcode, DL, VT, Ops); 6207 } 6208 6209 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6210 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6211 SDValue N5) { 6212 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6213 return getNode(Opcode, DL, VT, Ops); 6214 } 6215 6216 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6217 /// the incoming stack arguments to be loaded from the stack. 6218 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6219 SmallVector<SDValue, 8> ArgChains; 6220 6221 // Include the original chain at the beginning of the list. When this is 6222 // used by target LowerCall hooks, this helps legalize find the 6223 // CALLSEQ_BEGIN node. 6224 ArgChains.push_back(Chain); 6225 6226 // Add a chain value for each stack argument. 6227 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6228 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6229 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6230 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6231 if (FI->getIndex() < 0) 6232 ArgChains.push_back(SDValue(L, 1)); 6233 6234 // Build a tokenfactor for all the chains. 6235 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6236 } 6237 6238 /// getMemsetValue - Vectorized representation of the memset value 6239 /// operand. 6240 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6241 const SDLoc &dl) { 6242 assert(!Value.isUndef()); 6243 6244 unsigned NumBits = VT.getScalarSizeInBits(); 6245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6246 assert(C->getAPIntValue().getBitWidth() == 8); 6247 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6248 if (VT.isInteger()) { 6249 bool IsOpaque = VT.getSizeInBits() > 64 || 6250 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6251 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6252 } 6253 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6254 VT); 6255 } 6256 6257 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6258 EVT IntVT = VT.getScalarType(); 6259 if (!IntVT.isInteger()) 6260 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6261 6262 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6263 if (NumBits > 8) { 6264 // Use a multiplication with 0x010101... to extend the input to the 6265 // required length. 6266 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6267 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6268 DAG.getConstant(Magic, dl, IntVT)); 6269 } 6270 6271 if (VT != Value.getValueType() && !VT.isInteger()) 6272 Value = DAG.getBitcast(VT.getScalarType(), Value); 6273 if (VT != Value.getValueType()) 6274 Value = DAG.getSplatBuildVector(VT, dl, Value); 6275 6276 return Value; 6277 } 6278 6279 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6280 /// used when a memcpy is turned into a memset when the source is a constant 6281 /// string ptr. 6282 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6283 const TargetLowering &TLI, 6284 const ConstantDataArraySlice &Slice) { 6285 // Handle vector with all elements zero. 6286 if (Slice.Array == nullptr) { 6287 if (VT.isInteger()) 6288 return DAG.getConstant(0, dl, VT); 6289 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6290 return DAG.getConstantFP(0.0, dl, VT); 6291 if (VT.isVector()) { 6292 unsigned NumElts = VT.getVectorNumElements(); 6293 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6294 return DAG.getNode(ISD::BITCAST, dl, VT, 6295 DAG.getConstant(0, dl, 6296 EVT::getVectorVT(*DAG.getContext(), 6297 EltVT, NumElts))); 6298 } 6299 llvm_unreachable("Expected type!"); 6300 } 6301 6302 assert(!VT.isVector() && "Can't handle vector type here!"); 6303 unsigned NumVTBits = VT.getSizeInBits(); 6304 unsigned NumVTBytes = NumVTBits / 8; 6305 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6306 6307 APInt Val(NumVTBits, 0); 6308 if (DAG.getDataLayout().isLittleEndian()) { 6309 for (unsigned i = 0; i != NumBytes; ++i) 6310 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6311 } else { 6312 for (unsigned i = 0; i != NumBytes; ++i) 6313 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6314 } 6315 6316 // If the "cost" of materializing the integer immediate is less than the cost 6317 // of a load, then it is cost effective to turn the load into the immediate. 6318 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6319 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6320 return DAG.getConstant(Val, dl, VT); 6321 return SDValue(nullptr, 0); 6322 } 6323 6324 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6325 const SDLoc &DL, 6326 const SDNodeFlags Flags) { 6327 EVT VT = Base.getValueType(); 6328 SDValue Index; 6329 6330 if (Offset.isScalable()) 6331 Index = getVScale(DL, Base.getValueType(), 6332 APInt(Base.getValueSizeInBits().getFixedSize(), 6333 Offset.getKnownMinSize())); 6334 else 6335 Index = getConstant(Offset.getFixedSize(), DL, VT); 6336 6337 return getMemBasePlusOffset(Base, Index, DL, Flags); 6338 } 6339 6340 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6341 const SDLoc &DL, 6342 const SDNodeFlags Flags) { 6343 assert(Offset.getValueType().isInteger()); 6344 EVT BasePtrVT = Ptr.getValueType(); 6345 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6346 } 6347 6348 /// Returns true if memcpy source is constant data. 6349 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6350 uint64_t SrcDelta = 0; 6351 GlobalAddressSDNode *G = nullptr; 6352 if (Src.getOpcode() == ISD::GlobalAddress) 6353 G = cast<GlobalAddressSDNode>(Src); 6354 else if (Src.getOpcode() == ISD::ADD && 6355 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6356 Src.getOperand(1).getOpcode() == ISD::Constant) { 6357 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6358 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6359 } 6360 if (!G) 6361 return false; 6362 6363 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6364 SrcDelta + G->getOffset()); 6365 } 6366 6367 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6368 SelectionDAG &DAG) { 6369 // On Darwin, -Os means optimize for size without hurting performance, so 6370 // only really optimize for size when -Oz (MinSize) is used. 6371 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6372 return MF.getFunction().hasMinSize(); 6373 return DAG.shouldOptForSize(); 6374 } 6375 6376 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6377 SmallVector<SDValue, 32> &OutChains, unsigned From, 6378 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6379 SmallVector<SDValue, 16> &OutStoreChains) { 6380 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6381 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6382 SmallVector<SDValue, 16> GluedLoadChains; 6383 for (unsigned i = From; i < To; ++i) { 6384 OutChains.push_back(OutLoadChains[i]); 6385 GluedLoadChains.push_back(OutLoadChains[i]); 6386 } 6387 6388 // Chain for all loads. 6389 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6390 GluedLoadChains); 6391 6392 for (unsigned i = From; i < To; ++i) { 6393 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6394 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6395 ST->getBasePtr(), ST->getMemoryVT(), 6396 ST->getMemOperand()); 6397 OutChains.push_back(NewStore); 6398 } 6399 } 6400 6401 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6402 SDValue Chain, SDValue Dst, SDValue Src, 6403 uint64_t Size, Align Alignment, 6404 bool isVol, bool AlwaysInline, 6405 MachinePointerInfo DstPtrInfo, 6406 MachinePointerInfo SrcPtrInfo, 6407 const AAMDNodes &AAInfo) { 6408 // Turn a memcpy of undef to nop. 6409 // FIXME: We need to honor volatile even is Src is undef. 6410 if (Src.isUndef()) 6411 return Chain; 6412 6413 // Expand memcpy to a series of load and store ops if the size operand falls 6414 // below a certain threshold. 6415 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6416 // rather than maybe a humongous number of loads and stores. 6417 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6418 const DataLayout &DL = DAG.getDataLayout(); 6419 LLVMContext &C = *DAG.getContext(); 6420 std::vector<EVT> MemOps; 6421 bool DstAlignCanChange = false; 6422 MachineFunction &MF = DAG.getMachineFunction(); 6423 MachineFrameInfo &MFI = MF.getFrameInfo(); 6424 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6425 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6426 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6427 DstAlignCanChange = true; 6428 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6429 if (!SrcAlign || Alignment > *SrcAlign) 6430 SrcAlign = Alignment; 6431 assert(SrcAlign && "SrcAlign must be set"); 6432 ConstantDataArraySlice Slice; 6433 // If marked as volatile, perform a copy even when marked as constant. 6434 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6435 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6436 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6437 const MemOp Op = isZeroConstant 6438 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6439 /*IsZeroMemset*/ true, isVol) 6440 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6441 *SrcAlign, isVol, CopyFromConstant); 6442 if (!TLI.findOptimalMemOpLowering( 6443 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6444 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6445 return SDValue(); 6446 6447 if (DstAlignCanChange) { 6448 Type *Ty = MemOps[0].getTypeForEVT(C); 6449 Align NewAlign = DL.getABITypeAlign(Ty); 6450 6451 // Don't promote to an alignment that would require dynamic stack 6452 // realignment. 6453 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6454 if (!TRI->hasStackRealignment(MF)) 6455 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6456 NewAlign = NewAlign / 2; 6457 6458 if (NewAlign > Alignment) { 6459 // Give the stack frame object a larger alignment if needed. 6460 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6461 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6462 Alignment = NewAlign; 6463 } 6464 } 6465 6466 // Prepare AAInfo for loads/stores after lowering this memcpy. 6467 AAMDNodes NewAAInfo = AAInfo; 6468 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6469 6470 MachineMemOperand::Flags MMOFlags = 6471 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6472 SmallVector<SDValue, 16> OutLoadChains; 6473 SmallVector<SDValue, 16> OutStoreChains; 6474 SmallVector<SDValue, 32> OutChains; 6475 unsigned NumMemOps = MemOps.size(); 6476 uint64_t SrcOff = 0, DstOff = 0; 6477 for (unsigned i = 0; i != NumMemOps; ++i) { 6478 EVT VT = MemOps[i]; 6479 unsigned VTSize = VT.getSizeInBits() / 8; 6480 SDValue Value, Store; 6481 6482 if (VTSize > Size) { 6483 // Issuing an unaligned load / store pair that overlaps with the previous 6484 // pair. Adjust the offset accordingly. 6485 assert(i == NumMemOps-1 && i != 0); 6486 SrcOff -= VTSize - Size; 6487 DstOff -= VTSize - Size; 6488 } 6489 6490 if (CopyFromConstant && 6491 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6492 // It's unlikely a store of a vector immediate can be done in a single 6493 // instruction. It would require a load from a constantpool first. 6494 // We only handle zero vectors here. 6495 // FIXME: Handle other cases where store of vector immediate is done in 6496 // a single instruction. 6497 ConstantDataArraySlice SubSlice; 6498 if (SrcOff < Slice.Length) { 6499 SubSlice = Slice; 6500 SubSlice.move(SrcOff); 6501 } else { 6502 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6503 SubSlice.Array = nullptr; 6504 SubSlice.Offset = 0; 6505 SubSlice.Length = VTSize; 6506 } 6507 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6508 if (Value.getNode()) { 6509 Store = DAG.getStore( 6510 Chain, dl, Value, 6511 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6512 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6513 OutChains.push_back(Store); 6514 } 6515 } 6516 6517 if (!Store.getNode()) { 6518 // The type might not be legal for the target. This should only happen 6519 // if the type is smaller than a legal type, as on PPC, so the right 6520 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6521 // to Load/Store if NVT==VT. 6522 // FIXME does the case above also need this? 6523 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6524 assert(NVT.bitsGE(VT)); 6525 6526 bool isDereferenceable = 6527 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6528 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6529 if (isDereferenceable) 6530 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6531 6532 Value = DAG.getExtLoad( 6533 ISD::EXTLOAD, dl, NVT, Chain, 6534 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6535 SrcPtrInfo.getWithOffset(SrcOff), VT, 6536 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6537 OutLoadChains.push_back(Value.getValue(1)); 6538 6539 Store = DAG.getTruncStore( 6540 Chain, dl, Value, 6541 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6542 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6543 OutStoreChains.push_back(Store); 6544 } 6545 SrcOff += VTSize; 6546 DstOff += VTSize; 6547 Size -= VTSize; 6548 } 6549 6550 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6551 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6552 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6553 6554 if (NumLdStInMemcpy) { 6555 // It may be that memcpy might be converted to memset if it's memcpy 6556 // of constants. In such a case, we won't have loads and stores, but 6557 // just stores. In the absence of loads, there is nothing to gang up. 6558 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6559 // If target does not care, just leave as it. 6560 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6561 OutChains.push_back(OutLoadChains[i]); 6562 OutChains.push_back(OutStoreChains[i]); 6563 } 6564 } else { 6565 // Ld/St less than/equal limit set by target. 6566 if (NumLdStInMemcpy <= GluedLdStLimit) { 6567 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6568 NumLdStInMemcpy, OutLoadChains, 6569 OutStoreChains); 6570 } else { 6571 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6572 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6573 unsigned GlueIter = 0; 6574 6575 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6576 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6577 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6578 6579 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6580 OutLoadChains, OutStoreChains); 6581 GlueIter += GluedLdStLimit; 6582 } 6583 6584 // Residual ld/st. 6585 if (RemainingLdStInMemcpy) { 6586 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6587 RemainingLdStInMemcpy, OutLoadChains, 6588 OutStoreChains); 6589 } 6590 } 6591 } 6592 } 6593 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6594 } 6595 6596 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6597 SDValue Chain, SDValue Dst, SDValue Src, 6598 uint64_t Size, Align Alignment, 6599 bool isVol, bool AlwaysInline, 6600 MachinePointerInfo DstPtrInfo, 6601 MachinePointerInfo SrcPtrInfo, 6602 const AAMDNodes &AAInfo) { 6603 // Turn a memmove of undef to nop. 6604 // FIXME: We need to honor volatile even is Src is undef. 6605 if (Src.isUndef()) 6606 return Chain; 6607 6608 // Expand memmove to a series of load and store ops if the size operand falls 6609 // below a certain threshold. 6610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6611 const DataLayout &DL = DAG.getDataLayout(); 6612 LLVMContext &C = *DAG.getContext(); 6613 std::vector<EVT> MemOps; 6614 bool DstAlignCanChange = false; 6615 MachineFunction &MF = DAG.getMachineFunction(); 6616 MachineFrameInfo &MFI = MF.getFrameInfo(); 6617 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6618 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6619 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6620 DstAlignCanChange = true; 6621 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6622 if (!SrcAlign || Alignment > *SrcAlign) 6623 SrcAlign = Alignment; 6624 assert(SrcAlign && "SrcAlign must be set"); 6625 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6626 if (!TLI.findOptimalMemOpLowering( 6627 MemOps, Limit, 6628 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6629 /*IsVolatile*/ true), 6630 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6631 MF.getFunction().getAttributes())) 6632 return SDValue(); 6633 6634 if (DstAlignCanChange) { 6635 Type *Ty = MemOps[0].getTypeForEVT(C); 6636 Align NewAlign = DL.getABITypeAlign(Ty); 6637 if (NewAlign > Alignment) { 6638 // Give the stack frame object a larger alignment if needed. 6639 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6640 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6641 Alignment = NewAlign; 6642 } 6643 } 6644 6645 // Prepare AAInfo for loads/stores after lowering this memmove. 6646 AAMDNodes NewAAInfo = AAInfo; 6647 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6648 6649 MachineMemOperand::Flags MMOFlags = 6650 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6651 uint64_t SrcOff = 0, DstOff = 0; 6652 SmallVector<SDValue, 8> LoadValues; 6653 SmallVector<SDValue, 8> LoadChains; 6654 SmallVector<SDValue, 8> OutChains; 6655 unsigned NumMemOps = MemOps.size(); 6656 for (unsigned i = 0; i < NumMemOps; i++) { 6657 EVT VT = MemOps[i]; 6658 unsigned VTSize = VT.getSizeInBits() / 8; 6659 SDValue Value; 6660 6661 bool isDereferenceable = 6662 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6663 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6664 if (isDereferenceable) 6665 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6666 6667 Value = DAG.getLoad( 6668 VT, dl, Chain, 6669 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6670 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6671 LoadValues.push_back(Value); 6672 LoadChains.push_back(Value.getValue(1)); 6673 SrcOff += VTSize; 6674 } 6675 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6676 OutChains.clear(); 6677 for (unsigned i = 0; i < NumMemOps; i++) { 6678 EVT VT = MemOps[i]; 6679 unsigned VTSize = VT.getSizeInBits() / 8; 6680 SDValue Store; 6681 6682 Store = DAG.getStore( 6683 Chain, dl, LoadValues[i], 6684 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6685 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6686 OutChains.push_back(Store); 6687 DstOff += VTSize; 6688 } 6689 6690 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6691 } 6692 6693 /// Lower the call to 'memset' intrinsic function into a series of store 6694 /// operations. 6695 /// 6696 /// \param DAG Selection DAG where lowered code is placed. 6697 /// \param dl Link to corresponding IR location. 6698 /// \param Chain Control flow dependency. 6699 /// \param Dst Pointer to destination memory location. 6700 /// \param Src Value of byte to write into the memory. 6701 /// \param Size Number of bytes to write. 6702 /// \param Alignment Alignment of the destination in bytes. 6703 /// \param isVol True if destination is volatile. 6704 /// \param DstPtrInfo IR information on the memory pointer. 6705 /// \returns New head in the control flow, if lowering was successful, empty 6706 /// SDValue otherwise. 6707 /// 6708 /// The function tries to replace 'llvm.memset' intrinsic with several store 6709 /// operations and value calculation code. This is usually profitable for small 6710 /// memory size. 6711 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6712 SDValue Chain, SDValue Dst, SDValue Src, 6713 uint64_t Size, Align Alignment, bool isVol, 6714 MachinePointerInfo DstPtrInfo, 6715 const AAMDNodes &AAInfo) { 6716 // Turn a memset of undef to nop. 6717 // FIXME: We need to honor volatile even is Src is undef. 6718 if (Src.isUndef()) 6719 return Chain; 6720 6721 // Expand memset to a series of load/store ops if the size operand 6722 // falls below a certain threshold. 6723 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6724 std::vector<EVT> MemOps; 6725 bool DstAlignCanChange = false; 6726 MachineFunction &MF = DAG.getMachineFunction(); 6727 MachineFrameInfo &MFI = MF.getFrameInfo(); 6728 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6729 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6730 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6731 DstAlignCanChange = true; 6732 bool IsZeroVal = 6733 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6734 if (!TLI.findOptimalMemOpLowering( 6735 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6736 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6737 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6738 return SDValue(); 6739 6740 if (DstAlignCanChange) { 6741 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6742 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6743 if (NewAlign > Alignment) { 6744 // Give the stack frame object a larger alignment if needed. 6745 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6746 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6747 Alignment = NewAlign; 6748 } 6749 } 6750 6751 SmallVector<SDValue, 8> OutChains; 6752 uint64_t DstOff = 0; 6753 unsigned NumMemOps = MemOps.size(); 6754 6755 // Find the largest store and generate the bit pattern for it. 6756 EVT LargestVT = MemOps[0]; 6757 for (unsigned i = 1; i < NumMemOps; i++) 6758 if (MemOps[i].bitsGT(LargestVT)) 6759 LargestVT = MemOps[i]; 6760 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6761 6762 // Prepare AAInfo for loads/stores after lowering this memset. 6763 AAMDNodes NewAAInfo = AAInfo; 6764 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6765 6766 for (unsigned i = 0; i < NumMemOps; i++) { 6767 EVT VT = MemOps[i]; 6768 unsigned VTSize = VT.getSizeInBits() / 8; 6769 if (VTSize > Size) { 6770 // Issuing an unaligned load / store pair that overlaps with the previous 6771 // pair. Adjust the offset accordingly. 6772 assert(i == NumMemOps-1 && i != 0); 6773 DstOff -= VTSize - Size; 6774 } 6775 6776 // If this store is smaller than the largest store see whether we can get 6777 // the smaller value for free with a truncate. 6778 SDValue Value = MemSetValue; 6779 if (VT.bitsLT(LargestVT)) { 6780 if (!LargestVT.isVector() && !VT.isVector() && 6781 TLI.isTruncateFree(LargestVT, VT)) 6782 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6783 else 6784 Value = getMemsetValue(Src, VT, DAG, dl); 6785 } 6786 assert(Value.getValueType() == VT && "Value with wrong type."); 6787 SDValue Store = DAG.getStore( 6788 Chain, dl, Value, 6789 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6790 DstPtrInfo.getWithOffset(DstOff), Alignment, 6791 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6792 NewAAInfo); 6793 OutChains.push_back(Store); 6794 DstOff += VT.getSizeInBits() / 8; 6795 Size -= VTSize; 6796 } 6797 6798 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6799 } 6800 6801 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6802 unsigned AS) { 6803 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6804 // pointer operands can be losslessly bitcasted to pointers of address space 0 6805 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6806 report_fatal_error("cannot lower memory intrinsic in address space " + 6807 Twine(AS)); 6808 } 6809 } 6810 6811 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6812 SDValue Src, SDValue Size, Align Alignment, 6813 bool isVol, bool AlwaysInline, bool isTailCall, 6814 MachinePointerInfo DstPtrInfo, 6815 MachinePointerInfo SrcPtrInfo, 6816 const AAMDNodes &AAInfo) { 6817 // Check to see if we should lower the memcpy to loads and stores first. 6818 // For cases within the target-specified limits, this is the best choice. 6819 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6820 if (ConstantSize) { 6821 // Memcpy with size zero? Just return the original chain. 6822 if (ConstantSize->isNullValue()) 6823 return Chain; 6824 6825 SDValue Result = getMemcpyLoadsAndStores( 6826 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6827 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6828 if (Result.getNode()) 6829 return Result; 6830 } 6831 6832 // Then check to see if we should lower the memcpy with target-specific 6833 // code. If the target chooses to do this, this is the next best. 6834 if (TSI) { 6835 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6836 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6837 DstPtrInfo, SrcPtrInfo); 6838 if (Result.getNode()) 6839 return Result; 6840 } 6841 6842 // If we really need inline code and the target declined to provide it, 6843 // use a (potentially long) sequence of loads and stores. 6844 if (AlwaysInline) { 6845 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6846 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6847 ConstantSize->getZExtValue(), Alignment, 6848 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6849 } 6850 6851 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6852 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6853 6854 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6855 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6856 // respect volatile, so they may do things like read or write memory 6857 // beyond the given memory regions. But fixing this isn't easy, and most 6858 // people don't care. 6859 6860 // Emit a library call. 6861 TargetLowering::ArgListTy Args; 6862 TargetLowering::ArgListEntry Entry; 6863 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6864 Entry.Node = Dst; Args.push_back(Entry); 6865 Entry.Node = Src; Args.push_back(Entry); 6866 6867 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6868 Entry.Node = Size; Args.push_back(Entry); 6869 // FIXME: pass in SDLoc 6870 TargetLowering::CallLoweringInfo CLI(*this); 6871 CLI.setDebugLoc(dl) 6872 .setChain(Chain) 6873 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6874 Dst.getValueType().getTypeForEVT(*getContext()), 6875 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6876 TLI->getPointerTy(getDataLayout())), 6877 std::move(Args)) 6878 .setDiscardResult() 6879 .setTailCall(isTailCall); 6880 6881 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6882 return CallResult.second; 6883 } 6884 6885 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6886 SDValue Dst, unsigned DstAlign, 6887 SDValue Src, unsigned SrcAlign, 6888 SDValue Size, Type *SizeTy, 6889 unsigned ElemSz, bool isTailCall, 6890 MachinePointerInfo DstPtrInfo, 6891 MachinePointerInfo SrcPtrInfo) { 6892 // Emit a library call. 6893 TargetLowering::ArgListTy Args; 6894 TargetLowering::ArgListEntry Entry; 6895 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6896 Entry.Node = Dst; 6897 Args.push_back(Entry); 6898 6899 Entry.Node = Src; 6900 Args.push_back(Entry); 6901 6902 Entry.Ty = SizeTy; 6903 Entry.Node = Size; 6904 Args.push_back(Entry); 6905 6906 RTLIB::Libcall LibraryCall = 6907 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6908 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6909 report_fatal_error("Unsupported element size"); 6910 6911 TargetLowering::CallLoweringInfo CLI(*this); 6912 CLI.setDebugLoc(dl) 6913 .setChain(Chain) 6914 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6915 Type::getVoidTy(*getContext()), 6916 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6917 TLI->getPointerTy(getDataLayout())), 6918 std::move(Args)) 6919 .setDiscardResult() 6920 .setTailCall(isTailCall); 6921 6922 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6923 return CallResult.second; 6924 } 6925 6926 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6927 SDValue Src, SDValue Size, Align Alignment, 6928 bool isVol, bool isTailCall, 6929 MachinePointerInfo DstPtrInfo, 6930 MachinePointerInfo SrcPtrInfo, 6931 const AAMDNodes &AAInfo) { 6932 // Check to see if we should lower the memmove to loads and stores first. 6933 // For cases within the target-specified limits, this is the best choice. 6934 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6935 if (ConstantSize) { 6936 // Memmove with size zero? Just return the original chain. 6937 if (ConstantSize->isNullValue()) 6938 return Chain; 6939 6940 SDValue Result = getMemmoveLoadsAndStores( 6941 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6942 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6943 if (Result.getNode()) 6944 return Result; 6945 } 6946 6947 // Then check to see if we should lower the memmove with target-specific 6948 // code. If the target chooses to do this, this is the next best. 6949 if (TSI) { 6950 SDValue Result = 6951 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6952 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6953 if (Result.getNode()) 6954 return Result; 6955 } 6956 6957 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6958 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6959 6960 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6961 // not be safe. See memcpy above for more details. 6962 6963 // Emit a library call. 6964 TargetLowering::ArgListTy Args; 6965 TargetLowering::ArgListEntry Entry; 6966 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6967 Entry.Node = Dst; Args.push_back(Entry); 6968 Entry.Node = Src; Args.push_back(Entry); 6969 6970 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6971 Entry.Node = Size; Args.push_back(Entry); 6972 // FIXME: pass in SDLoc 6973 TargetLowering::CallLoweringInfo CLI(*this); 6974 CLI.setDebugLoc(dl) 6975 .setChain(Chain) 6976 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6977 Dst.getValueType().getTypeForEVT(*getContext()), 6978 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6979 TLI->getPointerTy(getDataLayout())), 6980 std::move(Args)) 6981 .setDiscardResult() 6982 .setTailCall(isTailCall); 6983 6984 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6985 return CallResult.second; 6986 } 6987 6988 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6989 SDValue Dst, unsigned DstAlign, 6990 SDValue Src, unsigned SrcAlign, 6991 SDValue Size, Type *SizeTy, 6992 unsigned ElemSz, bool isTailCall, 6993 MachinePointerInfo DstPtrInfo, 6994 MachinePointerInfo SrcPtrInfo) { 6995 // Emit a library call. 6996 TargetLowering::ArgListTy Args; 6997 TargetLowering::ArgListEntry Entry; 6998 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6999 Entry.Node = Dst; 7000 Args.push_back(Entry); 7001 7002 Entry.Node = Src; 7003 Args.push_back(Entry); 7004 7005 Entry.Ty = SizeTy; 7006 Entry.Node = Size; 7007 Args.push_back(Entry); 7008 7009 RTLIB::Libcall LibraryCall = 7010 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7011 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7012 report_fatal_error("Unsupported element size"); 7013 7014 TargetLowering::CallLoweringInfo CLI(*this); 7015 CLI.setDebugLoc(dl) 7016 .setChain(Chain) 7017 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7018 Type::getVoidTy(*getContext()), 7019 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7020 TLI->getPointerTy(getDataLayout())), 7021 std::move(Args)) 7022 .setDiscardResult() 7023 .setTailCall(isTailCall); 7024 7025 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7026 return CallResult.second; 7027 } 7028 7029 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7030 SDValue Src, SDValue Size, Align Alignment, 7031 bool isVol, bool isTailCall, 7032 MachinePointerInfo DstPtrInfo, 7033 const AAMDNodes &AAInfo) { 7034 // Check to see if we should lower the memset to stores first. 7035 // For cases within the target-specified limits, this is the best choice. 7036 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7037 if (ConstantSize) { 7038 // Memset with size zero? Just return the original chain. 7039 if (ConstantSize->isNullValue()) 7040 return Chain; 7041 7042 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7043 ConstantSize->getZExtValue(), Alignment, 7044 isVol, DstPtrInfo, AAInfo); 7045 7046 if (Result.getNode()) 7047 return Result; 7048 } 7049 7050 // Then check to see if we should lower the memset with target-specific 7051 // code. If the target chooses to do this, this is the next best. 7052 if (TSI) { 7053 SDValue Result = TSI->EmitTargetCodeForMemset( 7054 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7055 if (Result.getNode()) 7056 return Result; 7057 } 7058 7059 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7060 7061 // Emit a library call. 7062 TargetLowering::ArgListTy Args; 7063 TargetLowering::ArgListEntry Entry; 7064 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7065 Args.push_back(Entry); 7066 Entry.Node = Src; 7067 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7068 Args.push_back(Entry); 7069 Entry.Node = Size; 7070 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7071 Args.push_back(Entry); 7072 7073 // FIXME: pass in SDLoc 7074 TargetLowering::CallLoweringInfo CLI(*this); 7075 CLI.setDebugLoc(dl) 7076 .setChain(Chain) 7077 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7078 Dst.getValueType().getTypeForEVT(*getContext()), 7079 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7080 TLI->getPointerTy(getDataLayout())), 7081 std::move(Args)) 7082 .setDiscardResult() 7083 .setTailCall(isTailCall); 7084 7085 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7086 return CallResult.second; 7087 } 7088 7089 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7090 SDValue Dst, unsigned DstAlign, 7091 SDValue Value, SDValue Size, Type *SizeTy, 7092 unsigned ElemSz, bool isTailCall, 7093 MachinePointerInfo DstPtrInfo) { 7094 // Emit a library call. 7095 TargetLowering::ArgListTy Args; 7096 TargetLowering::ArgListEntry Entry; 7097 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7098 Entry.Node = Dst; 7099 Args.push_back(Entry); 7100 7101 Entry.Ty = Type::getInt8Ty(*getContext()); 7102 Entry.Node = Value; 7103 Args.push_back(Entry); 7104 7105 Entry.Ty = SizeTy; 7106 Entry.Node = Size; 7107 Args.push_back(Entry); 7108 7109 RTLIB::Libcall LibraryCall = 7110 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7111 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7112 report_fatal_error("Unsupported element size"); 7113 7114 TargetLowering::CallLoweringInfo CLI(*this); 7115 CLI.setDebugLoc(dl) 7116 .setChain(Chain) 7117 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7118 Type::getVoidTy(*getContext()), 7119 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7120 TLI->getPointerTy(getDataLayout())), 7121 std::move(Args)) 7122 .setDiscardResult() 7123 .setTailCall(isTailCall); 7124 7125 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7126 return CallResult.second; 7127 } 7128 7129 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7130 SDVTList VTList, ArrayRef<SDValue> Ops, 7131 MachineMemOperand *MMO) { 7132 FoldingSetNodeID ID; 7133 ID.AddInteger(MemVT.getRawBits()); 7134 AddNodeIDNode(ID, Opcode, VTList, Ops); 7135 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7136 void* IP = nullptr; 7137 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7138 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7139 return SDValue(E, 0); 7140 } 7141 7142 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7143 VTList, MemVT, MMO); 7144 createOperands(N, Ops); 7145 7146 CSEMap.InsertNode(N, IP); 7147 InsertNode(N); 7148 return SDValue(N, 0); 7149 } 7150 7151 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7152 EVT MemVT, SDVTList VTs, SDValue Chain, 7153 SDValue Ptr, SDValue Cmp, SDValue Swp, 7154 MachineMemOperand *MMO) { 7155 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7156 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7157 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7158 7159 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7160 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7161 } 7162 7163 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7164 SDValue Chain, SDValue Ptr, SDValue Val, 7165 MachineMemOperand *MMO) { 7166 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7167 Opcode == ISD::ATOMIC_LOAD_SUB || 7168 Opcode == ISD::ATOMIC_LOAD_AND || 7169 Opcode == ISD::ATOMIC_LOAD_CLR || 7170 Opcode == ISD::ATOMIC_LOAD_OR || 7171 Opcode == ISD::ATOMIC_LOAD_XOR || 7172 Opcode == ISD::ATOMIC_LOAD_NAND || 7173 Opcode == ISD::ATOMIC_LOAD_MIN || 7174 Opcode == ISD::ATOMIC_LOAD_MAX || 7175 Opcode == ISD::ATOMIC_LOAD_UMIN || 7176 Opcode == ISD::ATOMIC_LOAD_UMAX || 7177 Opcode == ISD::ATOMIC_LOAD_FADD || 7178 Opcode == ISD::ATOMIC_LOAD_FSUB || 7179 Opcode == ISD::ATOMIC_SWAP || 7180 Opcode == ISD::ATOMIC_STORE) && 7181 "Invalid Atomic Op"); 7182 7183 EVT VT = Val.getValueType(); 7184 7185 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7186 getVTList(VT, MVT::Other); 7187 SDValue Ops[] = {Chain, Ptr, Val}; 7188 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7189 } 7190 7191 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7192 EVT VT, SDValue Chain, SDValue Ptr, 7193 MachineMemOperand *MMO) { 7194 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7195 7196 SDVTList VTs = getVTList(VT, MVT::Other); 7197 SDValue Ops[] = {Chain, Ptr}; 7198 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7199 } 7200 7201 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7202 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7203 if (Ops.size() == 1) 7204 return Ops[0]; 7205 7206 SmallVector<EVT, 4> VTs; 7207 VTs.reserve(Ops.size()); 7208 for (const SDValue &Op : Ops) 7209 VTs.push_back(Op.getValueType()); 7210 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7211 } 7212 7213 SDValue SelectionDAG::getMemIntrinsicNode( 7214 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7215 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7216 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7217 if (!Size && MemVT.isScalableVector()) 7218 Size = MemoryLocation::UnknownSize; 7219 else if (!Size) 7220 Size = MemVT.getStoreSize(); 7221 7222 MachineFunction &MF = getMachineFunction(); 7223 MachineMemOperand *MMO = 7224 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7225 7226 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7227 } 7228 7229 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7230 SDVTList VTList, 7231 ArrayRef<SDValue> Ops, EVT MemVT, 7232 MachineMemOperand *MMO) { 7233 assert((Opcode == ISD::INTRINSIC_VOID || 7234 Opcode == ISD::INTRINSIC_W_CHAIN || 7235 Opcode == ISD::PREFETCH || 7236 ((int)Opcode <= std::numeric_limits<int>::max() && 7237 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7238 "Opcode is not a memory-accessing opcode!"); 7239 7240 // Memoize the node unless it returns a flag. 7241 MemIntrinsicSDNode *N; 7242 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7243 FoldingSetNodeID ID; 7244 AddNodeIDNode(ID, Opcode, VTList, Ops); 7245 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7246 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7247 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7248 void *IP = nullptr; 7249 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7250 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7251 return SDValue(E, 0); 7252 } 7253 7254 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7255 VTList, MemVT, MMO); 7256 createOperands(N, Ops); 7257 7258 CSEMap.InsertNode(N, IP); 7259 } else { 7260 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7261 VTList, MemVT, MMO); 7262 createOperands(N, Ops); 7263 } 7264 InsertNode(N); 7265 SDValue V(N, 0); 7266 NewSDValueDbgMsg(V, "Creating new node: ", this); 7267 return V; 7268 } 7269 7270 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7271 SDValue Chain, int FrameIndex, 7272 int64_t Size, int64_t Offset) { 7273 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7274 const auto VTs = getVTList(MVT::Other); 7275 SDValue Ops[2] = { 7276 Chain, 7277 getFrameIndex(FrameIndex, 7278 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7279 true)}; 7280 7281 FoldingSetNodeID ID; 7282 AddNodeIDNode(ID, Opcode, VTs, Ops); 7283 ID.AddInteger(FrameIndex); 7284 ID.AddInteger(Size); 7285 ID.AddInteger(Offset); 7286 void *IP = nullptr; 7287 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7288 return SDValue(E, 0); 7289 7290 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7291 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7292 createOperands(N, Ops); 7293 CSEMap.InsertNode(N, IP); 7294 InsertNode(N); 7295 SDValue V(N, 0); 7296 NewSDValueDbgMsg(V, "Creating new node: ", this); 7297 return V; 7298 } 7299 7300 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7301 uint64_t Guid, uint64_t Index, 7302 uint32_t Attr) { 7303 const unsigned Opcode = ISD::PSEUDO_PROBE; 7304 const auto VTs = getVTList(MVT::Other); 7305 SDValue Ops[] = {Chain}; 7306 FoldingSetNodeID ID; 7307 AddNodeIDNode(ID, Opcode, VTs, Ops); 7308 ID.AddInteger(Guid); 7309 ID.AddInteger(Index); 7310 void *IP = nullptr; 7311 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7312 return SDValue(E, 0); 7313 7314 auto *N = newSDNode<PseudoProbeSDNode>( 7315 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7316 createOperands(N, Ops); 7317 CSEMap.InsertNode(N, IP); 7318 InsertNode(N); 7319 SDValue V(N, 0); 7320 NewSDValueDbgMsg(V, "Creating new node: ", this); 7321 return V; 7322 } 7323 7324 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7325 /// MachinePointerInfo record from it. This is particularly useful because the 7326 /// code generator has many cases where it doesn't bother passing in a 7327 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7328 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7329 SelectionDAG &DAG, SDValue Ptr, 7330 int64_t Offset = 0) { 7331 // If this is FI+Offset, we can model it. 7332 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7333 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7334 FI->getIndex(), Offset); 7335 7336 // If this is (FI+Offset1)+Offset2, we can model it. 7337 if (Ptr.getOpcode() != ISD::ADD || 7338 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7339 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7340 return Info; 7341 7342 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7343 return MachinePointerInfo::getFixedStack( 7344 DAG.getMachineFunction(), FI, 7345 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7346 } 7347 7348 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7349 /// MachinePointerInfo record from it. This is particularly useful because the 7350 /// code generator has many cases where it doesn't bother passing in a 7351 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7352 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7353 SelectionDAG &DAG, SDValue Ptr, 7354 SDValue OffsetOp) { 7355 // If the 'Offset' value isn't a constant, we can't handle this. 7356 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7357 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7358 if (OffsetOp.isUndef()) 7359 return InferPointerInfo(Info, DAG, Ptr); 7360 return Info; 7361 } 7362 7363 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7364 EVT VT, const SDLoc &dl, SDValue Chain, 7365 SDValue Ptr, SDValue Offset, 7366 MachinePointerInfo PtrInfo, EVT MemVT, 7367 Align Alignment, 7368 MachineMemOperand::Flags MMOFlags, 7369 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7370 assert(Chain.getValueType() == MVT::Other && 7371 "Invalid chain type"); 7372 7373 MMOFlags |= MachineMemOperand::MOLoad; 7374 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7375 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7376 // clients. 7377 if (PtrInfo.V.isNull()) 7378 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7379 7380 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7381 MachineFunction &MF = getMachineFunction(); 7382 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7383 Alignment, AAInfo, Ranges); 7384 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7385 } 7386 7387 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7388 EVT VT, const SDLoc &dl, SDValue Chain, 7389 SDValue Ptr, SDValue Offset, EVT MemVT, 7390 MachineMemOperand *MMO) { 7391 if (VT == MemVT) { 7392 ExtType = ISD::NON_EXTLOAD; 7393 } else if (ExtType == ISD::NON_EXTLOAD) { 7394 assert(VT == MemVT && "Non-extending load from different memory type!"); 7395 } else { 7396 // Extending load. 7397 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7398 "Should only be an extending load, not truncating!"); 7399 assert(VT.isInteger() == MemVT.isInteger() && 7400 "Cannot convert from FP to Int or Int -> FP!"); 7401 assert(VT.isVector() == MemVT.isVector() && 7402 "Cannot use an ext load to convert to or from a vector!"); 7403 assert((!VT.isVector() || 7404 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7405 "Cannot use an ext load to change the number of vector elements!"); 7406 } 7407 7408 bool Indexed = AM != ISD::UNINDEXED; 7409 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7410 7411 SDVTList VTs = Indexed ? 7412 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7413 SDValue Ops[] = { Chain, Ptr, Offset }; 7414 FoldingSetNodeID ID; 7415 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7416 ID.AddInteger(MemVT.getRawBits()); 7417 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7418 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7419 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7420 void *IP = nullptr; 7421 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7422 cast<LoadSDNode>(E)->refineAlignment(MMO); 7423 return SDValue(E, 0); 7424 } 7425 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7426 ExtType, MemVT, MMO); 7427 createOperands(N, Ops); 7428 7429 CSEMap.InsertNode(N, IP); 7430 InsertNode(N); 7431 SDValue V(N, 0); 7432 NewSDValueDbgMsg(V, "Creating new node: ", this); 7433 return V; 7434 } 7435 7436 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7437 SDValue Ptr, MachinePointerInfo PtrInfo, 7438 MaybeAlign Alignment, 7439 MachineMemOperand::Flags MMOFlags, 7440 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7441 SDValue Undef = getUNDEF(Ptr.getValueType()); 7442 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7443 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7444 } 7445 7446 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7447 SDValue Ptr, MachineMemOperand *MMO) { 7448 SDValue Undef = getUNDEF(Ptr.getValueType()); 7449 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7450 VT, MMO); 7451 } 7452 7453 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7454 EVT VT, SDValue Chain, SDValue Ptr, 7455 MachinePointerInfo PtrInfo, EVT MemVT, 7456 MaybeAlign Alignment, 7457 MachineMemOperand::Flags MMOFlags, 7458 const AAMDNodes &AAInfo) { 7459 SDValue Undef = getUNDEF(Ptr.getValueType()); 7460 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7461 MemVT, Alignment, MMOFlags, AAInfo); 7462 } 7463 7464 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7465 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7466 MachineMemOperand *MMO) { 7467 SDValue Undef = getUNDEF(Ptr.getValueType()); 7468 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7469 MemVT, MMO); 7470 } 7471 7472 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7473 SDValue Base, SDValue Offset, 7474 ISD::MemIndexedMode AM) { 7475 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7476 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7477 // Don't propagate the invariant or dereferenceable flags. 7478 auto MMOFlags = 7479 LD->getMemOperand()->getFlags() & 7480 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7481 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7482 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7483 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7484 } 7485 7486 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7487 SDValue Ptr, MachinePointerInfo PtrInfo, 7488 Align Alignment, 7489 MachineMemOperand::Flags MMOFlags, 7490 const AAMDNodes &AAInfo) { 7491 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7492 7493 MMOFlags |= MachineMemOperand::MOStore; 7494 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7495 7496 if (PtrInfo.V.isNull()) 7497 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7498 7499 MachineFunction &MF = getMachineFunction(); 7500 uint64_t Size = 7501 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7502 MachineMemOperand *MMO = 7503 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7504 return getStore(Chain, dl, Val, Ptr, MMO); 7505 } 7506 7507 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7508 SDValue Ptr, MachineMemOperand *MMO) { 7509 assert(Chain.getValueType() == MVT::Other && 7510 "Invalid chain type"); 7511 EVT VT = Val.getValueType(); 7512 SDVTList VTs = getVTList(MVT::Other); 7513 SDValue Undef = getUNDEF(Ptr.getValueType()); 7514 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7515 FoldingSetNodeID ID; 7516 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7517 ID.AddInteger(VT.getRawBits()); 7518 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7519 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7520 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7521 void *IP = nullptr; 7522 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7523 cast<StoreSDNode>(E)->refineAlignment(MMO); 7524 return SDValue(E, 0); 7525 } 7526 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7527 ISD::UNINDEXED, false, VT, MMO); 7528 createOperands(N, Ops); 7529 7530 CSEMap.InsertNode(N, IP); 7531 InsertNode(N); 7532 SDValue V(N, 0); 7533 NewSDValueDbgMsg(V, "Creating new node: ", this); 7534 return V; 7535 } 7536 7537 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7538 SDValue Ptr, MachinePointerInfo PtrInfo, 7539 EVT SVT, Align Alignment, 7540 MachineMemOperand::Flags MMOFlags, 7541 const AAMDNodes &AAInfo) { 7542 assert(Chain.getValueType() == MVT::Other && 7543 "Invalid chain type"); 7544 7545 MMOFlags |= MachineMemOperand::MOStore; 7546 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7547 7548 if (PtrInfo.V.isNull()) 7549 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7550 7551 MachineFunction &MF = getMachineFunction(); 7552 MachineMemOperand *MMO = MF.getMachineMemOperand( 7553 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7554 Alignment, AAInfo); 7555 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7556 } 7557 7558 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7559 SDValue Ptr, EVT SVT, 7560 MachineMemOperand *MMO) { 7561 EVT VT = Val.getValueType(); 7562 7563 assert(Chain.getValueType() == MVT::Other && 7564 "Invalid chain type"); 7565 if (VT == SVT) 7566 return getStore(Chain, dl, Val, Ptr, MMO); 7567 7568 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7569 "Should only be a truncating store, not extending!"); 7570 assert(VT.isInteger() == SVT.isInteger() && 7571 "Can't do FP-INT conversion!"); 7572 assert(VT.isVector() == SVT.isVector() && 7573 "Cannot use trunc store to convert to or from a vector!"); 7574 assert((!VT.isVector() || 7575 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7576 "Cannot use trunc store to change the number of vector elements!"); 7577 7578 SDVTList VTs = getVTList(MVT::Other); 7579 SDValue Undef = getUNDEF(Ptr.getValueType()); 7580 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7581 FoldingSetNodeID ID; 7582 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7583 ID.AddInteger(SVT.getRawBits()); 7584 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7585 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7586 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7587 void *IP = nullptr; 7588 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7589 cast<StoreSDNode>(E)->refineAlignment(MMO); 7590 return SDValue(E, 0); 7591 } 7592 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7593 ISD::UNINDEXED, true, SVT, MMO); 7594 createOperands(N, Ops); 7595 7596 CSEMap.InsertNode(N, IP); 7597 InsertNode(N); 7598 SDValue V(N, 0); 7599 NewSDValueDbgMsg(V, "Creating new node: ", this); 7600 return V; 7601 } 7602 7603 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7604 SDValue Base, SDValue Offset, 7605 ISD::MemIndexedMode AM) { 7606 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7607 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7608 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7609 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7610 FoldingSetNodeID ID; 7611 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7612 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7613 ID.AddInteger(ST->getRawSubclassData()); 7614 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7615 void *IP = nullptr; 7616 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7617 return SDValue(E, 0); 7618 7619 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7620 ST->isTruncatingStore(), ST->getMemoryVT(), 7621 ST->getMemOperand()); 7622 createOperands(N, Ops); 7623 7624 CSEMap.InsertNode(N, IP); 7625 InsertNode(N); 7626 SDValue V(N, 0); 7627 NewSDValueDbgMsg(V, "Creating new node: ", this); 7628 return V; 7629 } 7630 7631 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7632 SDValue Base, SDValue Offset, SDValue Mask, 7633 SDValue PassThru, EVT MemVT, 7634 MachineMemOperand *MMO, 7635 ISD::MemIndexedMode AM, 7636 ISD::LoadExtType ExtTy, bool isExpanding) { 7637 bool Indexed = AM != ISD::UNINDEXED; 7638 assert((Indexed || Offset.isUndef()) && 7639 "Unindexed masked load with an offset!"); 7640 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7641 : getVTList(VT, MVT::Other); 7642 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7643 FoldingSetNodeID ID; 7644 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7645 ID.AddInteger(MemVT.getRawBits()); 7646 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7647 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7648 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7649 void *IP = nullptr; 7650 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7651 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7652 return SDValue(E, 0); 7653 } 7654 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7655 AM, ExtTy, isExpanding, MemVT, MMO); 7656 createOperands(N, Ops); 7657 7658 CSEMap.InsertNode(N, IP); 7659 InsertNode(N); 7660 SDValue V(N, 0); 7661 NewSDValueDbgMsg(V, "Creating new node: ", this); 7662 return V; 7663 } 7664 7665 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7666 SDValue Base, SDValue Offset, 7667 ISD::MemIndexedMode AM) { 7668 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7669 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7670 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7671 Offset, LD->getMask(), LD->getPassThru(), 7672 LD->getMemoryVT(), LD->getMemOperand(), AM, 7673 LD->getExtensionType(), LD->isExpandingLoad()); 7674 } 7675 7676 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7677 SDValue Val, SDValue Base, SDValue Offset, 7678 SDValue Mask, EVT MemVT, 7679 MachineMemOperand *MMO, 7680 ISD::MemIndexedMode AM, bool IsTruncating, 7681 bool IsCompressing) { 7682 assert(Chain.getValueType() == MVT::Other && 7683 "Invalid chain type"); 7684 bool Indexed = AM != ISD::UNINDEXED; 7685 assert((Indexed || Offset.isUndef()) && 7686 "Unindexed masked store with an offset!"); 7687 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7688 : getVTList(MVT::Other); 7689 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7690 FoldingSetNodeID ID; 7691 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7692 ID.AddInteger(MemVT.getRawBits()); 7693 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7694 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7695 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7696 void *IP = nullptr; 7697 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7698 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7699 return SDValue(E, 0); 7700 } 7701 auto *N = 7702 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7703 IsTruncating, IsCompressing, MemVT, MMO); 7704 createOperands(N, Ops); 7705 7706 CSEMap.InsertNode(N, IP); 7707 InsertNode(N); 7708 SDValue V(N, 0); 7709 NewSDValueDbgMsg(V, "Creating new node: ", this); 7710 return V; 7711 } 7712 7713 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7714 SDValue Base, SDValue Offset, 7715 ISD::MemIndexedMode AM) { 7716 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7717 assert(ST->getOffset().isUndef() && 7718 "Masked store is already a indexed store!"); 7719 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7720 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7721 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7722 } 7723 7724 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 7725 ArrayRef<SDValue> Ops, 7726 MachineMemOperand *MMO, 7727 ISD::MemIndexType IndexType, 7728 ISD::LoadExtType ExtTy) { 7729 assert(Ops.size() == 6 && "Incompatible number of operands"); 7730 7731 FoldingSetNodeID ID; 7732 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7733 ID.AddInteger(MemVT.getRawBits()); 7734 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7735 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 7736 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7737 void *IP = nullptr; 7738 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7739 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7740 return SDValue(E, 0); 7741 } 7742 7743 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 7744 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7745 VTs, MemVT, MMO, IndexType, ExtTy); 7746 createOperands(N, Ops); 7747 7748 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7749 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7750 assert(N->getMask().getValueType().getVectorElementCount() == 7751 N->getValueType(0).getVectorElementCount() && 7752 "Vector width mismatch between mask and data"); 7753 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7754 N->getValueType(0).getVectorElementCount().isScalable() && 7755 "Scalable flags of index and data do not match"); 7756 assert(ElementCount::isKnownGE( 7757 N->getIndex().getValueType().getVectorElementCount(), 7758 N->getValueType(0).getVectorElementCount()) && 7759 "Vector width mismatch between index and data"); 7760 assert(isa<ConstantSDNode>(N->getScale()) && 7761 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7762 "Scale should be a constant power of 2"); 7763 7764 CSEMap.InsertNode(N, IP); 7765 InsertNode(N); 7766 SDValue V(N, 0); 7767 NewSDValueDbgMsg(V, "Creating new node: ", this); 7768 return V; 7769 } 7770 7771 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 7772 ArrayRef<SDValue> Ops, 7773 MachineMemOperand *MMO, 7774 ISD::MemIndexType IndexType, 7775 bool IsTrunc) { 7776 assert(Ops.size() == 6 && "Incompatible number of operands"); 7777 7778 FoldingSetNodeID ID; 7779 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7780 ID.AddInteger(MemVT.getRawBits()); 7781 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7782 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 7783 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7784 void *IP = nullptr; 7785 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7786 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7787 return SDValue(E, 0); 7788 } 7789 7790 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 7791 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7792 VTs, MemVT, MMO, IndexType, IsTrunc); 7793 createOperands(N, Ops); 7794 7795 assert(N->getMask().getValueType().getVectorElementCount() == 7796 N->getValue().getValueType().getVectorElementCount() && 7797 "Vector width mismatch between mask and data"); 7798 assert( 7799 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7800 N->getValue().getValueType().getVectorElementCount().isScalable() && 7801 "Scalable flags of index and data do not match"); 7802 assert(ElementCount::isKnownGE( 7803 N->getIndex().getValueType().getVectorElementCount(), 7804 N->getValue().getValueType().getVectorElementCount()) && 7805 "Vector width mismatch between index and data"); 7806 assert(isa<ConstantSDNode>(N->getScale()) && 7807 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7808 "Scale should be a constant power of 2"); 7809 7810 CSEMap.InsertNode(N, IP); 7811 InsertNode(N); 7812 SDValue V(N, 0); 7813 NewSDValueDbgMsg(V, "Creating new node: ", this); 7814 return V; 7815 } 7816 7817 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7818 // select undef, T, F --> T (if T is a constant), otherwise F 7819 // select, ?, undef, F --> F 7820 // select, ?, T, undef --> T 7821 if (Cond.isUndef()) 7822 return isConstantValueOfAnyType(T) ? T : F; 7823 if (T.isUndef()) 7824 return F; 7825 if (F.isUndef()) 7826 return T; 7827 7828 // select true, T, F --> T 7829 // select false, T, F --> F 7830 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7831 return CondC->isNullValue() ? F : T; 7832 7833 // TODO: This should simplify VSELECT with constant condition using something 7834 // like this (but check boolean contents to be complete?): 7835 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7836 // return T; 7837 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7838 // return F; 7839 7840 // select ?, T, T --> T 7841 if (T == F) 7842 return T; 7843 7844 return SDValue(); 7845 } 7846 7847 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7848 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7849 if (X.isUndef()) 7850 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7851 // shift X, undef --> undef (because it may shift by the bitwidth) 7852 if (Y.isUndef()) 7853 return getUNDEF(X.getValueType()); 7854 7855 // shift 0, Y --> 0 7856 // shift X, 0 --> X 7857 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7858 return X; 7859 7860 // shift X, C >= bitwidth(X) --> undef 7861 // All vector elements must be too big (or undef) to avoid partial undefs. 7862 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7863 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7864 }; 7865 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7866 return getUNDEF(X.getValueType()); 7867 7868 return SDValue(); 7869 } 7870 7871 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7872 SDNodeFlags Flags) { 7873 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7874 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7875 // operation is poison. That result can be relaxed to undef. 7876 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7877 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7878 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7879 (YC && YC->getValueAPF().isNaN()); 7880 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7881 (YC && YC->getValueAPF().isInfinity()); 7882 7883 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7884 return getUNDEF(X.getValueType()); 7885 7886 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7887 return getUNDEF(X.getValueType()); 7888 7889 if (!YC) 7890 return SDValue(); 7891 7892 // X + -0.0 --> X 7893 if (Opcode == ISD::FADD) 7894 if (YC->getValueAPF().isNegZero()) 7895 return X; 7896 7897 // X - +0.0 --> X 7898 if (Opcode == ISD::FSUB) 7899 if (YC->getValueAPF().isPosZero()) 7900 return X; 7901 7902 // X * 1.0 --> X 7903 // X / 1.0 --> X 7904 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7905 if (YC->getValueAPF().isExactlyValue(1.0)) 7906 return X; 7907 7908 // X * 0.0 --> 0.0 7909 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7910 if (YC->getValueAPF().isZero()) 7911 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7912 7913 return SDValue(); 7914 } 7915 7916 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7917 SDValue Ptr, SDValue SV, unsigned Align) { 7918 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7919 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7920 } 7921 7922 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7923 ArrayRef<SDUse> Ops) { 7924 switch (Ops.size()) { 7925 case 0: return getNode(Opcode, DL, VT); 7926 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7927 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7928 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7929 default: break; 7930 } 7931 7932 // Copy from an SDUse array into an SDValue array for use with 7933 // the regular getNode logic. 7934 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7935 return getNode(Opcode, DL, VT, NewOps); 7936 } 7937 7938 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7939 ArrayRef<SDValue> Ops) { 7940 SDNodeFlags Flags; 7941 if (Inserter) 7942 Flags = Inserter->getFlags(); 7943 return getNode(Opcode, DL, VT, Ops, Flags); 7944 } 7945 7946 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7947 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7948 unsigned NumOps = Ops.size(); 7949 switch (NumOps) { 7950 case 0: return getNode(Opcode, DL, VT); 7951 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7952 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7953 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7954 default: break; 7955 } 7956 7957 #ifndef NDEBUG 7958 for (auto &Op : Ops) 7959 assert(Op.getOpcode() != ISD::DELETED_NODE && 7960 "Operand is DELETED_NODE!"); 7961 #endif 7962 7963 switch (Opcode) { 7964 default: break; 7965 case ISD::BUILD_VECTOR: 7966 // Attempt to simplify BUILD_VECTOR. 7967 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7968 return V; 7969 break; 7970 case ISD::CONCAT_VECTORS: 7971 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7972 return V; 7973 break; 7974 case ISD::SELECT_CC: 7975 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7976 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7977 "LHS and RHS of condition must have same type!"); 7978 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7979 "True and False arms of SelectCC must have same type!"); 7980 assert(Ops[2].getValueType() == VT && 7981 "select_cc node must be of same type as true and false value!"); 7982 break; 7983 case ISD::BR_CC: 7984 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7985 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7986 "LHS/RHS of comparison should match types!"); 7987 break; 7988 } 7989 7990 // Memoize nodes. 7991 SDNode *N; 7992 SDVTList VTs = getVTList(VT); 7993 7994 if (VT != MVT::Glue) { 7995 FoldingSetNodeID ID; 7996 AddNodeIDNode(ID, Opcode, VTs, Ops); 7997 void *IP = nullptr; 7998 7999 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8000 return SDValue(E, 0); 8001 8002 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8003 createOperands(N, Ops); 8004 8005 CSEMap.InsertNode(N, IP); 8006 } else { 8007 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8008 createOperands(N, Ops); 8009 } 8010 8011 N->setFlags(Flags); 8012 InsertNode(N); 8013 SDValue V(N, 0); 8014 NewSDValueDbgMsg(V, "Creating new node: ", this); 8015 return V; 8016 } 8017 8018 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8019 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8020 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8021 } 8022 8023 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8024 ArrayRef<SDValue> Ops) { 8025 SDNodeFlags Flags; 8026 if (Inserter) 8027 Flags = Inserter->getFlags(); 8028 return getNode(Opcode, DL, VTList, Ops, Flags); 8029 } 8030 8031 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8032 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8033 if (VTList.NumVTs == 1) 8034 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8035 8036 #ifndef NDEBUG 8037 for (auto &Op : Ops) 8038 assert(Op.getOpcode() != ISD::DELETED_NODE && 8039 "Operand is DELETED_NODE!"); 8040 #endif 8041 8042 switch (Opcode) { 8043 case ISD::STRICT_FP_EXTEND: 8044 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8045 "Invalid STRICT_FP_EXTEND!"); 8046 assert(VTList.VTs[0].isFloatingPoint() && 8047 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8048 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8049 "STRICT_FP_EXTEND result type should be vector iff the operand " 8050 "type is vector!"); 8051 assert((!VTList.VTs[0].isVector() || 8052 VTList.VTs[0].getVectorNumElements() == 8053 Ops[1].getValueType().getVectorNumElements()) && 8054 "Vector element count mismatch!"); 8055 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8056 "Invalid fpext node, dst <= src!"); 8057 break; 8058 case ISD::STRICT_FP_ROUND: 8059 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8060 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8061 "STRICT_FP_ROUND result type should be vector iff the operand " 8062 "type is vector!"); 8063 assert((!VTList.VTs[0].isVector() || 8064 VTList.VTs[0].getVectorNumElements() == 8065 Ops[1].getValueType().getVectorNumElements()) && 8066 "Vector element count mismatch!"); 8067 assert(VTList.VTs[0].isFloatingPoint() && 8068 Ops[1].getValueType().isFloatingPoint() && 8069 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8070 isa<ConstantSDNode>(Ops[2]) && 8071 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8072 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8073 "Invalid STRICT_FP_ROUND!"); 8074 break; 8075 #if 0 8076 // FIXME: figure out how to safely handle things like 8077 // int foo(int x) { return 1 << (x & 255); } 8078 // int bar() { return foo(256); } 8079 case ISD::SRA_PARTS: 8080 case ISD::SRL_PARTS: 8081 case ISD::SHL_PARTS: 8082 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8083 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8084 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8085 else if (N3.getOpcode() == ISD::AND) 8086 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8087 // If the and is only masking out bits that cannot effect the shift, 8088 // eliminate the and. 8089 unsigned NumBits = VT.getScalarSizeInBits()*2; 8090 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8091 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8092 } 8093 break; 8094 #endif 8095 } 8096 8097 // Memoize the node unless it returns a flag. 8098 SDNode *N; 8099 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8100 FoldingSetNodeID ID; 8101 AddNodeIDNode(ID, Opcode, VTList, Ops); 8102 void *IP = nullptr; 8103 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8104 return SDValue(E, 0); 8105 8106 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8107 createOperands(N, Ops); 8108 CSEMap.InsertNode(N, IP); 8109 } else { 8110 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8111 createOperands(N, Ops); 8112 } 8113 8114 N->setFlags(Flags); 8115 InsertNode(N); 8116 SDValue V(N, 0); 8117 NewSDValueDbgMsg(V, "Creating new node: ", this); 8118 return V; 8119 } 8120 8121 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8122 SDVTList VTList) { 8123 return getNode(Opcode, DL, VTList, None); 8124 } 8125 8126 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8127 SDValue N1) { 8128 SDValue Ops[] = { N1 }; 8129 return getNode(Opcode, DL, VTList, Ops); 8130 } 8131 8132 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8133 SDValue N1, SDValue N2) { 8134 SDValue Ops[] = { N1, N2 }; 8135 return getNode(Opcode, DL, VTList, Ops); 8136 } 8137 8138 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8139 SDValue N1, SDValue N2, SDValue N3) { 8140 SDValue Ops[] = { N1, N2, N3 }; 8141 return getNode(Opcode, DL, VTList, Ops); 8142 } 8143 8144 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8145 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8146 SDValue Ops[] = { N1, N2, N3, N4 }; 8147 return getNode(Opcode, DL, VTList, Ops); 8148 } 8149 8150 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8151 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8152 SDValue N5) { 8153 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8154 return getNode(Opcode, DL, VTList, Ops); 8155 } 8156 8157 SDVTList SelectionDAG::getVTList(EVT VT) { 8158 return makeVTList(SDNode::getValueTypeList(VT), 1); 8159 } 8160 8161 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8162 FoldingSetNodeID ID; 8163 ID.AddInteger(2U); 8164 ID.AddInteger(VT1.getRawBits()); 8165 ID.AddInteger(VT2.getRawBits()); 8166 8167 void *IP = nullptr; 8168 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8169 if (!Result) { 8170 EVT *Array = Allocator.Allocate<EVT>(2); 8171 Array[0] = VT1; 8172 Array[1] = VT2; 8173 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8174 VTListMap.InsertNode(Result, IP); 8175 } 8176 return Result->getSDVTList(); 8177 } 8178 8179 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8180 FoldingSetNodeID ID; 8181 ID.AddInteger(3U); 8182 ID.AddInteger(VT1.getRawBits()); 8183 ID.AddInteger(VT2.getRawBits()); 8184 ID.AddInteger(VT3.getRawBits()); 8185 8186 void *IP = nullptr; 8187 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8188 if (!Result) { 8189 EVT *Array = Allocator.Allocate<EVT>(3); 8190 Array[0] = VT1; 8191 Array[1] = VT2; 8192 Array[2] = VT3; 8193 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8194 VTListMap.InsertNode(Result, IP); 8195 } 8196 return Result->getSDVTList(); 8197 } 8198 8199 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8200 FoldingSetNodeID ID; 8201 ID.AddInteger(4U); 8202 ID.AddInteger(VT1.getRawBits()); 8203 ID.AddInteger(VT2.getRawBits()); 8204 ID.AddInteger(VT3.getRawBits()); 8205 ID.AddInteger(VT4.getRawBits()); 8206 8207 void *IP = nullptr; 8208 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8209 if (!Result) { 8210 EVT *Array = Allocator.Allocate<EVT>(4); 8211 Array[0] = VT1; 8212 Array[1] = VT2; 8213 Array[2] = VT3; 8214 Array[3] = VT4; 8215 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8216 VTListMap.InsertNode(Result, IP); 8217 } 8218 return Result->getSDVTList(); 8219 } 8220 8221 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8222 unsigned NumVTs = VTs.size(); 8223 FoldingSetNodeID ID; 8224 ID.AddInteger(NumVTs); 8225 for (unsigned index = 0; index < NumVTs; index++) { 8226 ID.AddInteger(VTs[index].getRawBits()); 8227 } 8228 8229 void *IP = nullptr; 8230 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8231 if (!Result) { 8232 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8233 llvm::copy(VTs, Array); 8234 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8235 VTListMap.InsertNode(Result, IP); 8236 } 8237 return Result->getSDVTList(); 8238 } 8239 8240 8241 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8242 /// specified operands. If the resultant node already exists in the DAG, 8243 /// this does not modify the specified node, instead it returns the node that 8244 /// already exists. If the resultant node does not exist in the DAG, the 8245 /// input node is returned. As a degenerate case, if you specify the same 8246 /// input operands as the node already has, the input node is returned. 8247 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8248 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8249 8250 // Check to see if there is no change. 8251 if (Op == N->getOperand(0)) return N; 8252 8253 // See if the modified node already exists. 8254 void *InsertPos = nullptr; 8255 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8256 return Existing; 8257 8258 // Nope it doesn't. Remove the node from its current place in the maps. 8259 if (InsertPos) 8260 if (!RemoveNodeFromCSEMaps(N)) 8261 InsertPos = nullptr; 8262 8263 // Now we update the operands. 8264 N->OperandList[0].set(Op); 8265 8266 updateDivergence(N); 8267 // If this gets put into a CSE map, add it. 8268 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8269 return N; 8270 } 8271 8272 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8273 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8274 8275 // Check to see if there is no change. 8276 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8277 return N; // No operands changed, just return the input node. 8278 8279 // See if the modified node already exists. 8280 void *InsertPos = nullptr; 8281 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8282 return Existing; 8283 8284 // Nope it doesn't. Remove the node from its current place in the maps. 8285 if (InsertPos) 8286 if (!RemoveNodeFromCSEMaps(N)) 8287 InsertPos = nullptr; 8288 8289 // Now we update the operands. 8290 if (N->OperandList[0] != Op1) 8291 N->OperandList[0].set(Op1); 8292 if (N->OperandList[1] != Op2) 8293 N->OperandList[1].set(Op2); 8294 8295 updateDivergence(N); 8296 // If this gets put into a CSE map, add it. 8297 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8298 return N; 8299 } 8300 8301 SDNode *SelectionDAG:: 8302 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8303 SDValue Ops[] = { Op1, Op2, Op3 }; 8304 return UpdateNodeOperands(N, Ops); 8305 } 8306 8307 SDNode *SelectionDAG:: 8308 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8309 SDValue Op3, SDValue Op4) { 8310 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8311 return UpdateNodeOperands(N, Ops); 8312 } 8313 8314 SDNode *SelectionDAG:: 8315 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8316 SDValue Op3, SDValue Op4, SDValue Op5) { 8317 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8318 return UpdateNodeOperands(N, Ops); 8319 } 8320 8321 SDNode *SelectionDAG:: 8322 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8323 unsigned NumOps = Ops.size(); 8324 assert(N->getNumOperands() == NumOps && 8325 "Update with wrong number of operands"); 8326 8327 // If no operands changed just return the input node. 8328 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8329 return N; 8330 8331 // See if the modified node already exists. 8332 void *InsertPos = nullptr; 8333 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8334 return Existing; 8335 8336 // Nope it doesn't. Remove the node from its current place in the maps. 8337 if (InsertPos) 8338 if (!RemoveNodeFromCSEMaps(N)) 8339 InsertPos = nullptr; 8340 8341 // Now we update the operands. 8342 for (unsigned i = 0; i != NumOps; ++i) 8343 if (N->OperandList[i] != Ops[i]) 8344 N->OperandList[i].set(Ops[i]); 8345 8346 updateDivergence(N); 8347 // If this gets put into a CSE map, add it. 8348 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8349 return N; 8350 } 8351 8352 /// DropOperands - Release the operands and set this node to have 8353 /// zero operands. 8354 void SDNode::DropOperands() { 8355 // Unlike the code in MorphNodeTo that does this, we don't need to 8356 // watch for dead nodes here. 8357 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8358 SDUse &Use = *I++; 8359 Use.set(SDValue()); 8360 } 8361 } 8362 8363 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8364 ArrayRef<MachineMemOperand *> NewMemRefs) { 8365 if (NewMemRefs.empty()) { 8366 N->clearMemRefs(); 8367 return; 8368 } 8369 8370 // Check if we can avoid allocating by storing a single reference directly. 8371 if (NewMemRefs.size() == 1) { 8372 N->MemRefs = NewMemRefs[0]; 8373 N->NumMemRefs = 1; 8374 return; 8375 } 8376 8377 MachineMemOperand **MemRefsBuffer = 8378 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8379 llvm::copy(NewMemRefs, MemRefsBuffer); 8380 N->MemRefs = MemRefsBuffer; 8381 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8382 } 8383 8384 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8385 /// machine opcode. 8386 /// 8387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8388 EVT VT) { 8389 SDVTList VTs = getVTList(VT); 8390 return SelectNodeTo(N, MachineOpc, VTs, None); 8391 } 8392 8393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8394 EVT VT, SDValue Op1) { 8395 SDVTList VTs = getVTList(VT); 8396 SDValue Ops[] = { Op1 }; 8397 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8398 } 8399 8400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8401 EVT VT, SDValue Op1, 8402 SDValue Op2) { 8403 SDVTList VTs = getVTList(VT); 8404 SDValue Ops[] = { Op1, Op2 }; 8405 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8406 } 8407 8408 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8409 EVT VT, SDValue Op1, 8410 SDValue Op2, SDValue Op3) { 8411 SDVTList VTs = getVTList(VT); 8412 SDValue Ops[] = { Op1, Op2, Op3 }; 8413 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8414 } 8415 8416 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8417 EVT VT, ArrayRef<SDValue> Ops) { 8418 SDVTList VTs = getVTList(VT); 8419 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8420 } 8421 8422 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8423 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8424 SDVTList VTs = getVTList(VT1, VT2); 8425 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8426 } 8427 8428 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8429 EVT VT1, EVT VT2) { 8430 SDVTList VTs = getVTList(VT1, VT2); 8431 return SelectNodeTo(N, MachineOpc, VTs, None); 8432 } 8433 8434 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8435 EVT VT1, EVT VT2, EVT VT3, 8436 ArrayRef<SDValue> Ops) { 8437 SDVTList VTs = getVTList(VT1, VT2, VT3); 8438 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8439 } 8440 8441 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8442 EVT VT1, EVT VT2, 8443 SDValue Op1, SDValue Op2) { 8444 SDVTList VTs = getVTList(VT1, VT2); 8445 SDValue Ops[] = { Op1, Op2 }; 8446 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8447 } 8448 8449 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8450 SDVTList VTs,ArrayRef<SDValue> Ops) { 8451 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8452 // Reset the NodeID to -1. 8453 New->setNodeId(-1); 8454 if (New != N) { 8455 ReplaceAllUsesWith(N, New); 8456 RemoveDeadNode(N); 8457 } 8458 return New; 8459 } 8460 8461 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8462 /// the line number information on the merged node since it is not possible to 8463 /// preserve the information that operation is associated with multiple lines. 8464 /// This will make the debugger working better at -O0, were there is a higher 8465 /// probability having other instructions associated with that line. 8466 /// 8467 /// For IROrder, we keep the smaller of the two 8468 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8469 DebugLoc NLoc = N->getDebugLoc(); 8470 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8471 N->setDebugLoc(DebugLoc()); 8472 } 8473 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8474 N->setIROrder(Order); 8475 return N; 8476 } 8477 8478 /// MorphNodeTo - This *mutates* the specified node to have the specified 8479 /// return type, opcode, and operands. 8480 /// 8481 /// Note that MorphNodeTo returns the resultant node. If there is already a 8482 /// node of the specified opcode and operands, it returns that node instead of 8483 /// the current one. Note that the SDLoc need not be the same. 8484 /// 8485 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8486 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8487 /// node, and because it doesn't require CSE recalculation for any of 8488 /// the node's users. 8489 /// 8490 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8491 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8492 /// the legalizer which maintain worklists that would need to be updated when 8493 /// deleting things. 8494 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8495 SDVTList VTs, ArrayRef<SDValue> Ops) { 8496 // If an identical node already exists, use it. 8497 void *IP = nullptr; 8498 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8499 FoldingSetNodeID ID; 8500 AddNodeIDNode(ID, Opc, VTs, Ops); 8501 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8502 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8503 } 8504 8505 if (!RemoveNodeFromCSEMaps(N)) 8506 IP = nullptr; 8507 8508 // Start the morphing. 8509 N->NodeType = Opc; 8510 N->ValueList = VTs.VTs; 8511 N->NumValues = VTs.NumVTs; 8512 8513 // Clear the operands list, updating used nodes to remove this from their 8514 // use list. Keep track of any operands that become dead as a result. 8515 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8516 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8517 SDUse &Use = *I++; 8518 SDNode *Used = Use.getNode(); 8519 Use.set(SDValue()); 8520 if (Used->use_empty()) 8521 DeadNodeSet.insert(Used); 8522 } 8523 8524 // For MachineNode, initialize the memory references information. 8525 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8526 MN->clearMemRefs(); 8527 8528 // Swap for an appropriately sized array from the recycler. 8529 removeOperands(N); 8530 createOperands(N, Ops); 8531 8532 // Delete any nodes that are still dead after adding the uses for the 8533 // new operands. 8534 if (!DeadNodeSet.empty()) { 8535 SmallVector<SDNode *, 16> DeadNodes; 8536 for (SDNode *N : DeadNodeSet) 8537 if (N->use_empty()) 8538 DeadNodes.push_back(N); 8539 RemoveDeadNodes(DeadNodes); 8540 } 8541 8542 if (IP) 8543 CSEMap.InsertNode(N, IP); // Memoize the new node. 8544 return N; 8545 } 8546 8547 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8548 unsigned OrigOpc = Node->getOpcode(); 8549 unsigned NewOpc; 8550 switch (OrigOpc) { 8551 default: 8552 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8553 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8554 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8555 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8556 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8557 #include "llvm/IR/ConstrainedOps.def" 8558 } 8559 8560 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8561 8562 // We're taking this node out of the chain, so we need to re-link things. 8563 SDValue InputChain = Node->getOperand(0); 8564 SDValue OutputChain = SDValue(Node, 1); 8565 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8566 8567 SmallVector<SDValue, 3> Ops; 8568 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8569 Ops.push_back(Node->getOperand(i)); 8570 8571 SDVTList VTs = getVTList(Node->getValueType(0)); 8572 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8573 8574 // MorphNodeTo can operate in two ways: if an existing node with the 8575 // specified operands exists, it can just return it. Otherwise, it 8576 // updates the node in place to have the requested operands. 8577 if (Res == Node) { 8578 // If we updated the node in place, reset the node ID. To the isel, 8579 // this should be just like a newly allocated machine node. 8580 Res->setNodeId(-1); 8581 } else { 8582 ReplaceAllUsesWith(Node, Res); 8583 RemoveDeadNode(Node); 8584 } 8585 8586 return Res; 8587 } 8588 8589 /// getMachineNode - These are used for target selectors to create a new node 8590 /// with specified return type(s), MachineInstr opcode, and operands. 8591 /// 8592 /// Note that getMachineNode returns the resultant node. If there is already a 8593 /// node of the specified opcode and operands, it returns that node instead of 8594 /// the current one. 8595 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8596 EVT VT) { 8597 SDVTList VTs = getVTList(VT); 8598 return getMachineNode(Opcode, dl, VTs, None); 8599 } 8600 8601 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8602 EVT VT, SDValue Op1) { 8603 SDVTList VTs = getVTList(VT); 8604 SDValue Ops[] = { Op1 }; 8605 return getMachineNode(Opcode, dl, VTs, Ops); 8606 } 8607 8608 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8609 EVT VT, SDValue Op1, SDValue Op2) { 8610 SDVTList VTs = getVTList(VT); 8611 SDValue Ops[] = { Op1, Op2 }; 8612 return getMachineNode(Opcode, dl, VTs, Ops); 8613 } 8614 8615 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8616 EVT VT, SDValue Op1, SDValue Op2, 8617 SDValue Op3) { 8618 SDVTList VTs = getVTList(VT); 8619 SDValue Ops[] = { Op1, Op2, Op3 }; 8620 return getMachineNode(Opcode, dl, VTs, Ops); 8621 } 8622 8623 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8624 EVT VT, ArrayRef<SDValue> Ops) { 8625 SDVTList VTs = getVTList(VT); 8626 return getMachineNode(Opcode, dl, VTs, Ops); 8627 } 8628 8629 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8630 EVT VT1, EVT VT2, SDValue Op1, 8631 SDValue Op2) { 8632 SDVTList VTs = getVTList(VT1, VT2); 8633 SDValue Ops[] = { Op1, Op2 }; 8634 return getMachineNode(Opcode, dl, VTs, Ops); 8635 } 8636 8637 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8638 EVT VT1, EVT VT2, SDValue Op1, 8639 SDValue Op2, SDValue Op3) { 8640 SDVTList VTs = getVTList(VT1, VT2); 8641 SDValue Ops[] = { Op1, Op2, Op3 }; 8642 return getMachineNode(Opcode, dl, VTs, Ops); 8643 } 8644 8645 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8646 EVT VT1, EVT VT2, 8647 ArrayRef<SDValue> Ops) { 8648 SDVTList VTs = getVTList(VT1, VT2); 8649 return getMachineNode(Opcode, dl, VTs, Ops); 8650 } 8651 8652 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8653 EVT VT1, EVT VT2, EVT VT3, 8654 SDValue Op1, SDValue Op2) { 8655 SDVTList VTs = getVTList(VT1, VT2, VT3); 8656 SDValue Ops[] = { Op1, Op2 }; 8657 return getMachineNode(Opcode, dl, VTs, Ops); 8658 } 8659 8660 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8661 EVT VT1, EVT VT2, EVT VT3, 8662 SDValue Op1, SDValue Op2, 8663 SDValue Op3) { 8664 SDVTList VTs = getVTList(VT1, VT2, VT3); 8665 SDValue Ops[] = { Op1, Op2, Op3 }; 8666 return getMachineNode(Opcode, dl, VTs, Ops); 8667 } 8668 8669 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8670 EVT VT1, EVT VT2, EVT VT3, 8671 ArrayRef<SDValue> Ops) { 8672 SDVTList VTs = getVTList(VT1, VT2, VT3); 8673 return getMachineNode(Opcode, dl, VTs, Ops); 8674 } 8675 8676 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8677 ArrayRef<EVT> ResultTys, 8678 ArrayRef<SDValue> Ops) { 8679 SDVTList VTs = getVTList(ResultTys); 8680 return getMachineNode(Opcode, dl, VTs, Ops); 8681 } 8682 8683 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8684 SDVTList VTs, 8685 ArrayRef<SDValue> Ops) { 8686 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8687 MachineSDNode *N; 8688 void *IP = nullptr; 8689 8690 if (DoCSE) { 8691 FoldingSetNodeID ID; 8692 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8693 IP = nullptr; 8694 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8695 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8696 } 8697 } 8698 8699 // Allocate a new MachineSDNode. 8700 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8701 createOperands(N, Ops); 8702 8703 if (DoCSE) 8704 CSEMap.InsertNode(N, IP); 8705 8706 InsertNode(N); 8707 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8708 return N; 8709 } 8710 8711 /// getTargetExtractSubreg - A convenience function for creating 8712 /// TargetOpcode::EXTRACT_SUBREG nodes. 8713 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8714 SDValue Operand) { 8715 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8716 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8717 VT, Operand, SRIdxVal); 8718 return SDValue(Subreg, 0); 8719 } 8720 8721 /// getTargetInsertSubreg - A convenience function for creating 8722 /// TargetOpcode::INSERT_SUBREG nodes. 8723 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8724 SDValue Operand, SDValue Subreg) { 8725 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8726 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8727 VT, Operand, Subreg, SRIdxVal); 8728 return SDValue(Result, 0); 8729 } 8730 8731 /// getNodeIfExists - Get the specified node if it's already available, or 8732 /// else return NULL. 8733 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8734 ArrayRef<SDValue> Ops) { 8735 SDNodeFlags Flags; 8736 if (Inserter) 8737 Flags = Inserter->getFlags(); 8738 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8739 } 8740 8741 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8742 ArrayRef<SDValue> Ops, 8743 const SDNodeFlags Flags) { 8744 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8745 FoldingSetNodeID ID; 8746 AddNodeIDNode(ID, Opcode, VTList, Ops); 8747 void *IP = nullptr; 8748 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8749 E->intersectFlagsWith(Flags); 8750 return E; 8751 } 8752 } 8753 return nullptr; 8754 } 8755 8756 /// doesNodeExist - Check if a node exists without modifying its flags. 8757 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8758 ArrayRef<SDValue> Ops) { 8759 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8760 FoldingSetNodeID ID; 8761 AddNodeIDNode(ID, Opcode, VTList, Ops); 8762 void *IP = nullptr; 8763 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8764 return true; 8765 } 8766 return false; 8767 } 8768 8769 /// getDbgValue - Creates a SDDbgValue node. 8770 /// 8771 /// SDNode 8772 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8773 SDNode *N, unsigned R, bool IsIndirect, 8774 const DebugLoc &DL, unsigned O) { 8775 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8776 "Expected inlined-at fields to agree"); 8777 return new (DbgInfo->getAlloc()) 8778 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 8779 {}, IsIndirect, DL, O, 8780 /*IsVariadic=*/false); 8781 } 8782 8783 /// Constant 8784 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8785 DIExpression *Expr, 8786 const Value *C, 8787 const DebugLoc &DL, unsigned O) { 8788 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8789 "Expected inlined-at fields to agree"); 8790 return new (DbgInfo->getAlloc()) 8791 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 8792 /*IsIndirect=*/false, DL, O, 8793 /*IsVariadic=*/false); 8794 } 8795 8796 /// FrameIndex 8797 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8798 DIExpression *Expr, unsigned FI, 8799 bool IsIndirect, 8800 const DebugLoc &DL, 8801 unsigned O) { 8802 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8803 "Expected inlined-at fields to agree"); 8804 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 8805 } 8806 8807 /// FrameIndex with dependencies 8808 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8809 DIExpression *Expr, unsigned FI, 8810 ArrayRef<SDNode *> Dependencies, 8811 bool IsIndirect, 8812 const DebugLoc &DL, 8813 unsigned O) { 8814 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8815 "Expected inlined-at fields to agree"); 8816 return new (DbgInfo->getAlloc()) 8817 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 8818 Dependencies, IsIndirect, DL, O, 8819 /*IsVariadic=*/false); 8820 } 8821 8822 /// VReg 8823 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 8824 unsigned VReg, bool IsIndirect, 8825 const DebugLoc &DL, unsigned O) { 8826 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8827 "Expected inlined-at fields to agree"); 8828 return new (DbgInfo->getAlloc()) 8829 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 8830 {}, IsIndirect, DL, O, 8831 /*IsVariadic=*/false); 8832 } 8833 8834 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 8835 ArrayRef<SDDbgOperand> Locs, 8836 ArrayRef<SDNode *> Dependencies, 8837 bool IsIndirect, const DebugLoc &DL, 8838 unsigned O, bool IsVariadic) { 8839 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8840 "Expected inlined-at fields to agree"); 8841 return new (DbgInfo->getAlloc()) 8842 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 8843 DL, O, IsVariadic); 8844 } 8845 8846 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8847 unsigned OffsetInBits, unsigned SizeInBits, 8848 bool InvalidateDbg) { 8849 SDNode *FromNode = From.getNode(); 8850 SDNode *ToNode = To.getNode(); 8851 assert(FromNode && ToNode && "Can't modify dbg values"); 8852 8853 // PR35338 8854 // TODO: assert(From != To && "Redundant dbg value transfer"); 8855 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8856 if (From == To || FromNode == ToNode) 8857 return; 8858 8859 if (!FromNode->getHasDebugValue()) 8860 return; 8861 8862 SDDbgOperand FromLocOp = 8863 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 8864 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 8865 8866 SmallVector<SDDbgValue *, 2> ClonedDVs; 8867 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8868 if (Dbg->isInvalidated()) 8869 continue; 8870 8871 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8872 8873 // Create a new location ops vector that is equal to the old vector, but 8874 // with each instance of FromLocOp replaced with ToLocOp. 8875 bool Changed = false; 8876 auto NewLocOps = Dbg->copyLocationOps(); 8877 std::replace_if( 8878 NewLocOps.begin(), NewLocOps.end(), 8879 [&Changed, FromLocOp](const SDDbgOperand &Op) { 8880 bool Match = Op == FromLocOp; 8881 Changed |= Match; 8882 return Match; 8883 }, 8884 ToLocOp); 8885 // Ignore this SDDbgValue if we didn't find a matching location. 8886 if (!Changed) 8887 continue; 8888 8889 DIVariable *Var = Dbg->getVariable(); 8890 auto *Expr = Dbg->getExpression(); 8891 // If a fragment is requested, update the expression. 8892 if (SizeInBits) { 8893 // When splitting a larger (e.g., sign-extended) value whose 8894 // lower bits are described with an SDDbgValue, do not attempt 8895 // to transfer the SDDbgValue to the upper bits. 8896 if (auto FI = Expr->getFragmentInfo()) 8897 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8898 continue; 8899 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8900 SizeInBits); 8901 if (!Fragment) 8902 continue; 8903 Expr = *Fragment; 8904 } 8905 8906 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 8907 // Clone the SDDbgValue and move it to To. 8908 SDDbgValue *Clone = getDbgValueList( 8909 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 8910 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 8911 Dbg->isVariadic()); 8912 ClonedDVs.push_back(Clone); 8913 8914 if (InvalidateDbg) { 8915 // Invalidate value and indicate the SDDbgValue should not be emitted. 8916 Dbg->setIsInvalidated(); 8917 Dbg->setIsEmitted(); 8918 } 8919 } 8920 8921 for (SDDbgValue *Dbg : ClonedDVs) { 8922 assert(is_contained(Dbg->getSDNodes(), ToNode) && 8923 "Transferred DbgValues should depend on the new SDNode"); 8924 AddDbgValue(Dbg, false); 8925 } 8926 } 8927 8928 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8929 if (!N.getHasDebugValue()) 8930 return; 8931 8932 SmallVector<SDDbgValue *, 2> ClonedDVs; 8933 for (auto DV : GetDbgValues(&N)) { 8934 if (DV->isInvalidated()) 8935 continue; 8936 switch (N.getOpcode()) { 8937 default: 8938 break; 8939 case ISD::ADD: 8940 SDValue N0 = N.getOperand(0); 8941 SDValue N1 = N.getOperand(1); 8942 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8943 isConstantIntBuildVectorOrConstantInt(N1)) { 8944 uint64_t Offset = N.getConstantOperandVal(1); 8945 8946 // Rewrite an ADD constant node into a DIExpression. Since we are 8947 // performing arithmetic to compute the variable's *value* in the 8948 // DIExpression, we need to mark the expression with a 8949 // DW_OP_stack_value. 8950 auto *DIExpr = DV->getExpression(); 8951 auto NewLocOps = DV->copyLocationOps(); 8952 bool Changed = false; 8953 for (size_t i = 0; i < NewLocOps.size(); ++i) { 8954 // We're not given a ResNo to compare against because the whole 8955 // node is going away. We know that any ISD::ADD only has one 8956 // result, so we can assume any node match is using the result. 8957 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 8958 NewLocOps[i].getSDNode() != &N) 8959 continue; 8960 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 8961 SmallVector<uint64_t, 3> ExprOps; 8962 DIExpression::appendOffset(ExprOps, Offset); 8963 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 8964 Changed = true; 8965 } 8966 (void)Changed; 8967 assert(Changed && "Salvage target doesn't use N"); 8968 8969 auto AdditionalDependencies = DV->getAdditionalDependencies(); 8970 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 8971 NewLocOps, AdditionalDependencies, 8972 DV->isIndirect(), DV->getDebugLoc(), 8973 DV->getOrder(), DV->isVariadic()); 8974 ClonedDVs.push_back(Clone); 8975 DV->setIsInvalidated(); 8976 DV->setIsEmitted(); 8977 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8978 N0.getNode()->dumprFull(this); 8979 dbgs() << " into " << *DIExpr << '\n'); 8980 } 8981 } 8982 } 8983 8984 for (SDDbgValue *Dbg : ClonedDVs) { 8985 assert(!Dbg->getSDNodes().empty() && 8986 "Salvaged DbgValue should depend on a new SDNode"); 8987 AddDbgValue(Dbg, false); 8988 } 8989 } 8990 8991 /// Creates a SDDbgLabel node. 8992 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8993 const DebugLoc &DL, unsigned O) { 8994 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8995 "Expected inlined-at fields to agree"); 8996 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8997 } 8998 8999 namespace { 9000 9001 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9002 /// pointed to by a use iterator is deleted, increment the use iterator 9003 /// so that it doesn't dangle. 9004 /// 9005 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9006 SDNode::use_iterator &UI; 9007 SDNode::use_iterator &UE; 9008 9009 void NodeDeleted(SDNode *N, SDNode *E) override { 9010 // Increment the iterator as needed. 9011 while (UI != UE && N == *UI) 9012 ++UI; 9013 } 9014 9015 public: 9016 RAUWUpdateListener(SelectionDAG &d, 9017 SDNode::use_iterator &ui, 9018 SDNode::use_iterator &ue) 9019 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9020 }; 9021 9022 } // end anonymous namespace 9023 9024 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9025 /// This can cause recursive merging of nodes in the DAG. 9026 /// 9027 /// This version assumes From has a single result value. 9028 /// 9029 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9030 SDNode *From = FromN.getNode(); 9031 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9032 "Cannot replace with this method!"); 9033 assert(From != To.getNode() && "Cannot replace uses of with self"); 9034 9035 // Preserve Debug Values 9036 transferDbgValues(FromN, To); 9037 9038 // Iterate over all the existing uses of From. New uses will be added 9039 // to the beginning of the use list, which we avoid visiting. 9040 // This specifically avoids visiting uses of From that arise while the 9041 // replacement is happening, because any such uses would be the result 9042 // of CSE: If an existing node looks like From after one of its operands 9043 // is replaced by To, we don't want to replace of all its users with To 9044 // too. See PR3018 for more info. 9045 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9046 RAUWUpdateListener Listener(*this, UI, UE); 9047 while (UI != UE) { 9048 SDNode *User = *UI; 9049 9050 // This node is about to morph, remove its old self from the CSE maps. 9051 RemoveNodeFromCSEMaps(User); 9052 9053 // A user can appear in a use list multiple times, and when this 9054 // happens the uses are usually next to each other in the list. 9055 // To help reduce the number of CSE recomputations, process all 9056 // the uses of this user that we can find this way. 9057 do { 9058 SDUse &Use = UI.getUse(); 9059 ++UI; 9060 Use.set(To); 9061 if (To->isDivergent() != From->isDivergent()) 9062 updateDivergence(User); 9063 } while (UI != UE && *UI == User); 9064 // Now that we have modified User, add it back to the CSE maps. If it 9065 // already exists there, recursively merge the results together. 9066 AddModifiedNodeToCSEMaps(User); 9067 } 9068 9069 // If we just RAUW'd the root, take note. 9070 if (FromN == getRoot()) 9071 setRoot(To); 9072 } 9073 9074 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9075 /// This can cause recursive merging of nodes in the DAG. 9076 /// 9077 /// This version assumes that for each value of From, there is a 9078 /// corresponding value in To in the same position with the same type. 9079 /// 9080 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9081 #ifndef NDEBUG 9082 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9083 assert((!From->hasAnyUseOfValue(i) || 9084 From->getValueType(i) == To->getValueType(i)) && 9085 "Cannot use this version of ReplaceAllUsesWith!"); 9086 #endif 9087 9088 // Handle the trivial case. 9089 if (From == To) 9090 return; 9091 9092 // Preserve Debug Info. Only do this if there's a use. 9093 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9094 if (From->hasAnyUseOfValue(i)) { 9095 assert((i < To->getNumValues()) && "Invalid To location"); 9096 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9097 } 9098 9099 // Iterate over just the existing users of From. See the comments in 9100 // the ReplaceAllUsesWith above. 9101 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9102 RAUWUpdateListener Listener(*this, UI, UE); 9103 while (UI != UE) { 9104 SDNode *User = *UI; 9105 9106 // This node is about to morph, remove its old self from the CSE maps. 9107 RemoveNodeFromCSEMaps(User); 9108 9109 // A user can appear in a use list multiple times, and when this 9110 // happens the uses are usually next to each other in the list. 9111 // To help reduce the number of CSE recomputations, process all 9112 // the uses of this user that we can find this way. 9113 do { 9114 SDUse &Use = UI.getUse(); 9115 ++UI; 9116 Use.setNode(To); 9117 if (To->isDivergent() != From->isDivergent()) 9118 updateDivergence(User); 9119 } while (UI != UE && *UI == User); 9120 9121 // Now that we have modified User, add it back to the CSE maps. If it 9122 // already exists there, recursively merge the results together. 9123 AddModifiedNodeToCSEMaps(User); 9124 } 9125 9126 // If we just RAUW'd the root, take note. 9127 if (From == getRoot().getNode()) 9128 setRoot(SDValue(To, getRoot().getResNo())); 9129 } 9130 9131 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9132 /// This can cause recursive merging of nodes in the DAG. 9133 /// 9134 /// This version can replace From with any result values. To must match the 9135 /// number and types of values returned by From. 9136 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9137 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9138 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9139 9140 // Preserve Debug Info. 9141 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9142 transferDbgValues(SDValue(From, i), To[i]); 9143 9144 // Iterate over just the existing users of From. See the comments in 9145 // the ReplaceAllUsesWith above. 9146 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9147 RAUWUpdateListener Listener(*this, UI, UE); 9148 while (UI != UE) { 9149 SDNode *User = *UI; 9150 9151 // This node is about to morph, remove its old self from the CSE maps. 9152 RemoveNodeFromCSEMaps(User); 9153 9154 // A user can appear in a use list multiple times, and when this happens the 9155 // uses are usually next to each other in the list. To help reduce the 9156 // number of CSE and divergence recomputations, process all the uses of this 9157 // user that we can find this way. 9158 bool To_IsDivergent = false; 9159 do { 9160 SDUse &Use = UI.getUse(); 9161 const SDValue &ToOp = To[Use.getResNo()]; 9162 ++UI; 9163 Use.set(ToOp); 9164 To_IsDivergent |= ToOp->isDivergent(); 9165 } while (UI != UE && *UI == User); 9166 9167 if (To_IsDivergent != From->isDivergent()) 9168 updateDivergence(User); 9169 9170 // Now that we have modified User, add it back to the CSE maps. If it 9171 // already exists there, recursively merge the results together. 9172 AddModifiedNodeToCSEMaps(User); 9173 } 9174 9175 // If we just RAUW'd the root, take note. 9176 if (From == getRoot().getNode()) 9177 setRoot(SDValue(To[getRoot().getResNo()])); 9178 } 9179 9180 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9181 /// uses of other values produced by From.getNode() alone. The Deleted 9182 /// vector is handled the same way as for ReplaceAllUsesWith. 9183 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9184 // Handle the really simple, really trivial case efficiently. 9185 if (From == To) return; 9186 9187 // Handle the simple, trivial, case efficiently. 9188 if (From.getNode()->getNumValues() == 1) { 9189 ReplaceAllUsesWith(From, To); 9190 return; 9191 } 9192 9193 // Preserve Debug Info. 9194 transferDbgValues(From, To); 9195 9196 // Iterate over just the existing users of From. See the comments in 9197 // the ReplaceAllUsesWith above. 9198 SDNode::use_iterator UI = From.getNode()->use_begin(), 9199 UE = From.getNode()->use_end(); 9200 RAUWUpdateListener Listener(*this, UI, UE); 9201 while (UI != UE) { 9202 SDNode *User = *UI; 9203 bool UserRemovedFromCSEMaps = false; 9204 9205 // A user can appear in a use list multiple times, and when this 9206 // happens the uses are usually next to each other in the list. 9207 // To help reduce the number of CSE recomputations, process all 9208 // the uses of this user that we can find this way. 9209 do { 9210 SDUse &Use = UI.getUse(); 9211 9212 // Skip uses of different values from the same node. 9213 if (Use.getResNo() != From.getResNo()) { 9214 ++UI; 9215 continue; 9216 } 9217 9218 // If this node hasn't been modified yet, it's still in the CSE maps, 9219 // so remove its old self from the CSE maps. 9220 if (!UserRemovedFromCSEMaps) { 9221 RemoveNodeFromCSEMaps(User); 9222 UserRemovedFromCSEMaps = true; 9223 } 9224 9225 ++UI; 9226 Use.set(To); 9227 if (To->isDivergent() != From->isDivergent()) 9228 updateDivergence(User); 9229 } while (UI != UE && *UI == User); 9230 // We are iterating over all uses of the From node, so if a use 9231 // doesn't use the specific value, no changes are made. 9232 if (!UserRemovedFromCSEMaps) 9233 continue; 9234 9235 // Now that we have modified User, add it back to the CSE maps. If it 9236 // already exists there, recursively merge the results together. 9237 AddModifiedNodeToCSEMaps(User); 9238 } 9239 9240 // If we just RAUW'd the root, take note. 9241 if (From == getRoot()) 9242 setRoot(To); 9243 } 9244 9245 namespace { 9246 9247 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9248 /// to record information about a use. 9249 struct UseMemo { 9250 SDNode *User; 9251 unsigned Index; 9252 SDUse *Use; 9253 }; 9254 9255 /// operator< - Sort Memos by User. 9256 bool operator<(const UseMemo &L, const UseMemo &R) { 9257 return (intptr_t)L.User < (intptr_t)R.User; 9258 } 9259 9260 } // end anonymous namespace 9261 9262 bool SelectionDAG::calculateDivergence(SDNode *N) { 9263 if (TLI->isSDNodeAlwaysUniform(N)) { 9264 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9265 "Conflicting divergence information!"); 9266 return false; 9267 } 9268 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9269 return true; 9270 for (auto &Op : N->ops()) { 9271 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9272 return true; 9273 } 9274 return false; 9275 } 9276 9277 void SelectionDAG::updateDivergence(SDNode *N) { 9278 SmallVector<SDNode *, 16> Worklist(1, N); 9279 do { 9280 N = Worklist.pop_back_val(); 9281 bool IsDivergent = calculateDivergence(N); 9282 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9283 N->SDNodeBits.IsDivergent = IsDivergent; 9284 llvm::append_range(Worklist, N->uses()); 9285 } 9286 } while (!Worklist.empty()); 9287 } 9288 9289 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9290 DenseMap<SDNode *, unsigned> Degree; 9291 Order.reserve(AllNodes.size()); 9292 for (auto &N : allnodes()) { 9293 unsigned NOps = N.getNumOperands(); 9294 Degree[&N] = NOps; 9295 if (0 == NOps) 9296 Order.push_back(&N); 9297 } 9298 for (size_t I = 0; I != Order.size(); ++I) { 9299 SDNode *N = Order[I]; 9300 for (auto U : N->uses()) { 9301 unsigned &UnsortedOps = Degree[U]; 9302 if (0 == --UnsortedOps) 9303 Order.push_back(U); 9304 } 9305 } 9306 } 9307 9308 #ifndef NDEBUG 9309 void SelectionDAG::VerifyDAGDiverence() { 9310 std::vector<SDNode *> TopoOrder; 9311 CreateTopologicalOrder(TopoOrder); 9312 for (auto *N : TopoOrder) { 9313 assert(calculateDivergence(N) == N->isDivergent() && 9314 "Divergence bit inconsistency detected"); 9315 } 9316 } 9317 #endif 9318 9319 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9320 /// uses of other values produced by From.getNode() alone. The same value 9321 /// may appear in both the From and To list. The Deleted vector is 9322 /// handled the same way as for ReplaceAllUsesWith. 9323 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9324 const SDValue *To, 9325 unsigned Num){ 9326 // Handle the simple, trivial case efficiently. 9327 if (Num == 1) 9328 return ReplaceAllUsesOfValueWith(*From, *To); 9329 9330 transferDbgValues(*From, *To); 9331 9332 // Read up all the uses and make records of them. This helps 9333 // processing new uses that are introduced during the 9334 // replacement process. 9335 SmallVector<UseMemo, 4> Uses; 9336 for (unsigned i = 0; i != Num; ++i) { 9337 unsigned FromResNo = From[i].getResNo(); 9338 SDNode *FromNode = From[i].getNode(); 9339 for (SDNode::use_iterator UI = FromNode->use_begin(), 9340 E = FromNode->use_end(); UI != E; ++UI) { 9341 SDUse &Use = UI.getUse(); 9342 if (Use.getResNo() == FromResNo) { 9343 UseMemo Memo = { *UI, i, &Use }; 9344 Uses.push_back(Memo); 9345 } 9346 } 9347 } 9348 9349 // Sort the uses, so that all the uses from a given User are together. 9350 llvm::sort(Uses); 9351 9352 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9353 UseIndex != UseIndexEnd; ) { 9354 // We know that this user uses some value of From. If it is the right 9355 // value, update it. 9356 SDNode *User = Uses[UseIndex].User; 9357 9358 // This node is about to morph, remove its old self from the CSE maps. 9359 RemoveNodeFromCSEMaps(User); 9360 9361 // The Uses array is sorted, so all the uses for a given User 9362 // are next to each other in the list. 9363 // To help reduce the number of CSE recomputations, process all 9364 // the uses of this user that we can find this way. 9365 do { 9366 unsigned i = Uses[UseIndex].Index; 9367 SDUse &Use = *Uses[UseIndex].Use; 9368 ++UseIndex; 9369 9370 Use.set(To[i]); 9371 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9372 9373 // Now that we have modified User, add it back to the CSE maps. If it 9374 // already exists there, recursively merge the results together. 9375 AddModifiedNodeToCSEMaps(User); 9376 } 9377 } 9378 9379 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9380 /// based on their topological order. It returns the maximum id and a vector 9381 /// of the SDNodes* in assigned order by reference. 9382 unsigned SelectionDAG::AssignTopologicalOrder() { 9383 unsigned DAGSize = 0; 9384 9385 // SortedPos tracks the progress of the algorithm. Nodes before it are 9386 // sorted, nodes after it are unsorted. When the algorithm completes 9387 // it is at the end of the list. 9388 allnodes_iterator SortedPos = allnodes_begin(); 9389 9390 // Visit all the nodes. Move nodes with no operands to the front of 9391 // the list immediately. Annotate nodes that do have operands with their 9392 // operand count. Before we do this, the Node Id fields of the nodes 9393 // may contain arbitrary values. After, the Node Id fields for nodes 9394 // before SortedPos will contain the topological sort index, and the 9395 // Node Id fields for nodes At SortedPos and after will contain the 9396 // count of outstanding operands. 9397 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9398 SDNode *N = &*I++; 9399 checkForCycles(N, this); 9400 unsigned Degree = N->getNumOperands(); 9401 if (Degree == 0) { 9402 // A node with no uses, add it to the result array immediately. 9403 N->setNodeId(DAGSize++); 9404 allnodes_iterator Q(N); 9405 if (Q != SortedPos) 9406 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9407 assert(SortedPos != AllNodes.end() && "Overran node list"); 9408 ++SortedPos; 9409 } else { 9410 // Temporarily use the Node Id as scratch space for the degree count. 9411 N->setNodeId(Degree); 9412 } 9413 } 9414 9415 // Visit all the nodes. As we iterate, move nodes into sorted order, 9416 // such that by the time the end is reached all nodes will be sorted. 9417 for (SDNode &Node : allnodes()) { 9418 SDNode *N = &Node; 9419 checkForCycles(N, this); 9420 // N is in sorted position, so all its uses have one less operand 9421 // that needs to be sorted. 9422 for (SDNode *P : N->uses()) { 9423 unsigned Degree = P->getNodeId(); 9424 assert(Degree != 0 && "Invalid node degree"); 9425 --Degree; 9426 if (Degree == 0) { 9427 // All of P's operands are sorted, so P may sorted now. 9428 P->setNodeId(DAGSize++); 9429 if (P->getIterator() != SortedPos) 9430 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9431 assert(SortedPos != AllNodes.end() && "Overran node list"); 9432 ++SortedPos; 9433 } else { 9434 // Update P's outstanding operand count. 9435 P->setNodeId(Degree); 9436 } 9437 } 9438 if (Node.getIterator() == SortedPos) { 9439 #ifndef NDEBUG 9440 allnodes_iterator I(N); 9441 SDNode *S = &*++I; 9442 dbgs() << "Overran sorted position:\n"; 9443 S->dumprFull(this); dbgs() << "\n"; 9444 dbgs() << "Checking if this is due to cycles\n"; 9445 checkForCycles(this, true); 9446 #endif 9447 llvm_unreachable(nullptr); 9448 } 9449 } 9450 9451 assert(SortedPos == AllNodes.end() && 9452 "Topological sort incomplete!"); 9453 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9454 "First node in topological sort is not the entry token!"); 9455 assert(AllNodes.front().getNodeId() == 0 && 9456 "First node in topological sort has non-zero id!"); 9457 assert(AllNodes.front().getNumOperands() == 0 && 9458 "First node in topological sort has operands!"); 9459 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9460 "Last node in topologic sort has unexpected id!"); 9461 assert(AllNodes.back().use_empty() && 9462 "Last node in topologic sort has users!"); 9463 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9464 return DAGSize; 9465 } 9466 9467 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9468 /// value is produced by SD. 9469 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9470 for (SDNode *SD : DB->getSDNodes()) { 9471 if (!SD) 9472 continue; 9473 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9474 SD->setHasDebugValue(true); 9475 } 9476 DbgInfo->add(DB, isParameter); 9477 } 9478 9479 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9480 9481 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9482 SDValue NewMemOpChain) { 9483 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9484 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9485 // The new memory operation must have the same position as the old load in 9486 // terms of memory dependency. Create a TokenFactor for the old load and new 9487 // memory operation and update uses of the old load's output chain to use that 9488 // TokenFactor. 9489 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9490 return NewMemOpChain; 9491 9492 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9493 OldChain, NewMemOpChain); 9494 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9495 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9496 return TokenFactor; 9497 } 9498 9499 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9500 SDValue NewMemOp) { 9501 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9502 SDValue OldChain = SDValue(OldLoad, 1); 9503 SDValue NewMemOpChain = NewMemOp.getValue(1); 9504 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9505 } 9506 9507 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9508 Function **OutFunction) { 9509 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9510 9511 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9512 auto *Module = MF->getFunction().getParent(); 9513 auto *Function = Module->getFunction(Symbol); 9514 9515 if (OutFunction != nullptr) 9516 *OutFunction = Function; 9517 9518 if (Function != nullptr) { 9519 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9520 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9521 } 9522 9523 std::string ErrorStr; 9524 raw_string_ostream ErrorFormatter(ErrorStr); 9525 9526 ErrorFormatter << "Undefined external symbol "; 9527 ErrorFormatter << '"' << Symbol << '"'; 9528 ErrorFormatter.flush(); 9529 9530 report_fatal_error(ErrorStr); 9531 } 9532 9533 //===----------------------------------------------------------------------===// 9534 // SDNode Class 9535 //===----------------------------------------------------------------------===// 9536 9537 bool llvm::isNullConstant(SDValue V) { 9538 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9539 return Const != nullptr && Const->isNullValue(); 9540 } 9541 9542 bool llvm::isNullFPConstant(SDValue V) { 9543 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9544 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9545 } 9546 9547 bool llvm::isAllOnesConstant(SDValue V) { 9548 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9549 return Const != nullptr && Const->isAllOnesValue(); 9550 } 9551 9552 bool llvm::isOneConstant(SDValue V) { 9553 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9554 return Const != nullptr && Const->isOne(); 9555 } 9556 9557 SDValue llvm::peekThroughBitcasts(SDValue V) { 9558 while (V.getOpcode() == ISD::BITCAST) 9559 V = V.getOperand(0); 9560 return V; 9561 } 9562 9563 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9564 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9565 V = V.getOperand(0); 9566 return V; 9567 } 9568 9569 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9570 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9571 V = V.getOperand(0); 9572 return V; 9573 } 9574 9575 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9576 if (V.getOpcode() != ISD::XOR) 9577 return false; 9578 V = peekThroughBitcasts(V.getOperand(1)); 9579 unsigned NumBits = V.getScalarValueSizeInBits(); 9580 ConstantSDNode *C = 9581 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9582 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9583 } 9584 9585 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9586 bool AllowTruncation) { 9587 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9588 return CN; 9589 9590 // SplatVectors can truncate their operands. Ignore that case here unless 9591 // AllowTruncation is set. 9592 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9593 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9594 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9595 EVT CVT = CN->getValueType(0); 9596 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9597 if (AllowTruncation || CVT == VecEltVT) 9598 return CN; 9599 } 9600 } 9601 9602 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9603 BitVector UndefElements; 9604 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9605 9606 // BuildVectors can truncate their operands. Ignore that case here unless 9607 // AllowTruncation is set. 9608 if (CN && (UndefElements.none() || AllowUndefs)) { 9609 EVT CVT = CN->getValueType(0); 9610 EVT NSVT = N.getValueType().getScalarType(); 9611 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9612 if (AllowTruncation || (CVT == NSVT)) 9613 return CN; 9614 } 9615 } 9616 9617 return nullptr; 9618 } 9619 9620 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9621 bool AllowUndefs, 9622 bool AllowTruncation) { 9623 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9624 return CN; 9625 9626 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9627 BitVector UndefElements; 9628 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9629 9630 // BuildVectors can truncate their operands. Ignore that case here unless 9631 // AllowTruncation is set. 9632 if (CN && (UndefElements.none() || AllowUndefs)) { 9633 EVT CVT = CN->getValueType(0); 9634 EVT NSVT = N.getValueType().getScalarType(); 9635 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9636 if (AllowTruncation || (CVT == NSVT)) 9637 return CN; 9638 } 9639 } 9640 9641 return nullptr; 9642 } 9643 9644 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9645 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9646 return CN; 9647 9648 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9649 BitVector UndefElements; 9650 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9651 if (CN && (UndefElements.none() || AllowUndefs)) 9652 return CN; 9653 } 9654 9655 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9656 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9657 return CN; 9658 9659 return nullptr; 9660 } 9661 9662 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9663 const APInt &DemandedElts, 9664 bool AllowUndefs) { 9665 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9666 return CN; 9667 9668 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9669 BitVector UndefElements; 9670 ConstantFPSDNode *CN = 9671 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9672 if (CN && (UndefElements.none() || AllowUndefs)) 9673 return CN; 9674 } 9675 9676 return nullptr; 9677 } 9678 9679 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9680 // TODO: may want to use peekThroughBitcast() here. 9681 ConstantSDNode *C = 9682 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 9683 return C && C->isNullValue(); 9684 } 9685 9686 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9687 // TODO: may want to use peekThroughBitcast() here. 9688 unsigned BitWidth = N.getScalarValueSizeInBits(); 9689 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9690 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9691 } 9692 9693 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9694 N = peekThroughBitcasts(N); 9695 unsigned BitWidth = N.getScalarValueSizeInBits(); 9696 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9697 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9698 } 9699 9700 HandleSDNode::~HandleSDNode() { 9701 DropOperands(); 9702 } 9703 9704 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9705 const DebugLoc &DL, 9706 const GlobalValue *GA, EVT VT, 9707 int64_t o, unsigned TF) 9708 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9709 TheGlobal = GA; 9710 } 9711 9712 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9713 EVT VT, unsigned SrcAS, 9714 unsigned DestAS) 9715 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9716 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9717 9718 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9719 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9720 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9721 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9722 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9723 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9724 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9725 9726 // We check here that the size of the memory operand fits within the size of 9727 // the MMO. This is because the MMO might indicate only a possible address 9728 // range instead of specifying the affected memory addresses precisely. 9729 // TODO: Make MachineMemOperands aware of scalable vectors. 9730 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9731 "Size mismatch!"); 9732 } 9733 9734 /// Profile - Gather unique data for the node. 9735 /// 9736 void SDNode::Profile(FoldingSetNodeID &ID) const { 9737 AddNodeIDNode(ID, this); 9738 } 9739 9740 namespace { 9741 9742 struct EVTArray { 9743 std::vector<EVT> VTs; 9744 9745 EVTArray() { 9746 VTs.reserve(MVT::VALUETYPE_SIZE); 9747 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 9748 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9749 } 9750 }; 9751 9752 } // end anonymous namespace 9753 9754 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9755 static ManagedStatic<EVTArray> SimpleVTArray; 9756 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9757 9758 /// getValueTypeList - Return a pointer to the specified value type. 9759 /// 9760 const EVT *SDNode::getValueTypeList(EVT VT) { 9761 if (VT.isExtended()) { 9762 sys::SmartScopedLock<true> Lock(*VTMutex); 9763 return &(*EVTs->insert(VT).first); 9764 } 9765 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 9766 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9767 } 9768 9769 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9770 /// indicated value. This method ignores uses of other values defined by this 9771 /// operation. 9772 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9773 assert(Value < getNumValues() && "Bad value!"); 9774 9775 // TODO: Only iterate over uses of a given value of the node 9776 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9777 if (UI.getUse().getResNo() == Value) { 9778 if (NUses == 0) 9779 return false; 9780 --NUses; 9781 } 9782 } 9783 9784 // Found exactly the right number of uses? 9785 return NUses == 0; 9786 } 9787 9788 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9789 /// value. This method ignores uses of other values defined by this operation. 9790 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9791 assert(Value < getNumValues() && "Bad value!"); 9792 9793 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9794 if (UI.getUse().getResNo() == Value) 9795 return true; 9796 9797 return false; 9798 } 9799 9800 /// isOnlyUserOf - Return true if this node is the only use of N. 9801 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9802 bool Seen = false; 9803 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9804 SDNode *User = *I; 9805 if (User == this) 9806 Seen = true; 9807 else 9808 return false; 9809 } 9810 9811 return Seen; 9812 } 9813 9814 /// Return true if the only users of N are contained in Nodes. 9815 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9816 bool Seen = false; 9817 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9818 SDNode *User = *I; 9819 if (llvm::is_contained(Nodes, User)) 9820 Seen = true; 9821 else 9822 return false; 9823 } 9824 9825 return Seen; 9826 } 9827 9828 /// isOperand - Return true if this node is an operand of N. 9829 bool SDValue::isOperandOf(const SDNode *N) const { 9830 return is_contained(N->op_values(), *this); 9831 } 9832 9833 bool SDNode::isOperandOf(const SDNode *N) const { 9834 return any_of(N->op_values(), 9835 [this](SDValue Op) { return this == Op.getNode(); }); 9836 } 9837 9838 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9839 /// be a chain) reaches the specified operand without crossing any 9840 /// side-effecting instructions on any chain path. In practice, this looks 9841 /// through token factors and non-volatile loads. In order to remain efficient, 9842 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9843 /// 9844 /// Note that we only need to examine chains when we're searching for 9845 /// side-effects; SelectionDAG requires that all side-effects are represented 9846 /// by chains, even if another operand would force a specific ordering. This 9847 /// constraint is necessary to allow transformations like splitting loads. 9848 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9849 unsigned Depth) const { 9850 if (*this == Dest) return true; 9851 9852 // Don't search too deeply, we just want to be able to see through 9853 // TokenFactor's etc. 9854 if (Depth == 0) return false; 9855 9856 // If this is a token factor, all inputs to the TF happen in parallel. 9857 if (getOpcode() == ISD::TokenFactor) { 9858 // First, try a shallow search. 9859 if (is_contained((*this)->ops(), Dest)) { 9860 // We found the chain we want as an operand of this TokenFactor. 9861 // Essentially, we reach the chain without side-effects if we could 9862 // serialize the TokenFactor into a simple chain of operations with 9863 // Dest as the last operation. This is automatically true if the 9864 // chain has one use: there are no other ordering constraints. 9865 // If the chain has more than one use, we give up: some other 9866 // use of Dest might force a side-effect between Dest and the current 9867 // node. 9868 if (Dest.hasOneUse()) 9869 return true; 9870 } 9871 // Next, try a deep search: check whether every operand of the TokenFactor 9872 // reaches Dest. 9873 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9874 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9875 }); 9876 } 9877 9878 // Loads don't have side effects, look through them. 9879 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9880 if (Ld->isUnordered()) 9881 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9882 } 9883 return false; 9884 } 9885 9886 bool SDNode::hasPredecessor(const SDNode *N) const { 9887 SmallPtrSet<const SDNode *, 32> Visited; 9888 SmallVector<const SDNode *, 16> Worklist; 9889 Worklist.push_back(this); 9890 return hasPredecessorHelper(N, Visited, Worklist); 9891 } 9892 9893 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9894 this->Flags.intersectWith(Flags); 9895 } 9896 9897 SDValue 9898 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9899 ArrayRef<ISD::NodeType> CandidateBinOps, 9900 bool AllowPartials) { 9901 // The pattern must end in an extract from index 0. 9902 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9903 !isNullConstant(Extract->getOperand(1))) 9904 return SDValue(); 9905 9906 // Match against one of the candidate binary ops. 9907 SDValue Op = Extract->getOperand(0); 9908 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9909 return Op.getOpcode() == unsigned(BinOp); 9910 })) 9911 return SDValue(); 9912 9913 // Floating-point reductions may require relaxed constraints on the final step 9914 // of the reduction because they may reorder intermediate operations. 9915 unsigned CandidateBinOp = Op.getOpcode(); 9916 if (Op.getValueType().isFloatingPoint()) { 9917 SDNodeFlags Flags = Op->getFlags(); 9918 switch (CandidateBinOp) { 9919 case ISD::FADD: 9920 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9921 return SDValue(); 9922 break; 9923 default: 9924 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9925 } 9926 } 9927 9928 // Matching failed - attempt to see if we did enough stages that a partial 9929 // reduction from a subvector is possible. 9930 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9931 if (!AllowPartials || !Op) 9932 return SDValue(); 9933 EVT OpVT = Op.getValueType(); 9934 EVT OpSVT = OpVT.getScalarType(); 9935 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9936 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9937 return SDValue(); 9938 BinOp = (ISD::NodeType)CandidateBinOp; 9939 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9940 getVectorIdxConstant(0, SDLoc(Op))); 9941 }; 9942 9943 // At each stage, we're looking for something that looks like: 9944 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9945 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9946 // i32 undef, i32 undef, i32 undef, i32 undef> 9947 // %a = binop <8 x i32> %op, %s 9948 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9949 // we expect something like: 9950 // <4,5,6,7,u,u,u,u> 9951 // <2,3,u,u,u,u,u,u> 9952 // <1,u,u,u,u,u,u,u> 9953 // While a partial reduction match would be: 9954 // <2,3,u,u,u,u,u,u> 9955 // <1,u,u,u,u,u,u,u> 9956 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9957 SDValue PrevOp; 9958 for (unsigned i = 0; i < Stages; ++i) { 9959 unsigned MaskEnd = (1 << i); 9960 9961 if (Op.getOpcode() != CandidateBinOp) 9962 return PartialReduction(PrevOp, MaskEnd); 9963 9964 SDValue Op0 = Op.getOperand(0); 9965 SDValue Op1 = Op.getOperand(1); 9966 9967 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9968 if (Shuffle) { 9969 Op = Op1; 9970 } else { 9971 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9972 Op = Op0; 9973 } 9974 9975 // The first operand of the shuffle should be the same as the other operand 9976 // of the binop. 9977 if (!Shuffle || Shuffle->getOperand(0) != Op) 9978 return PartialReduction(PrevOp, MaskEnd); 9979 9980 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9981 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9982 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9983 return PartialReduction(PrevOp, MaskEnd); 9984 9985 PrevOp = Op; 9986 } 9987 9988 // Handle subvector reductions, which tend to appear after the shuffle 9989 // reduction stages. 9990 while (Op.getOpcode() == CandidateBinOp) { 9991 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9992 SDValue Op0 = Op.getOperand(0); 9993 SDValue Op1 = Op.getOperand(1); 9994 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9995 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9996 Op0.getOperand(0) != Op1.getOperand(0)) 9997 break; 9998 SDValue Src = Op0.getOperand(0); 9999 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10000 if (NumSrcElts != (2 * NumElts)) 10001 break; 10002 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10003 Op1.getConstantOperandAPInt(1) == NumElts) && 10004 !(Op1.getConstantOperandAPInt(1) == 0 && 10005 Op0.getConstantOperandAPInt(1) == NumElts)) 10006 break; 10007 Op = Src; 10008 } 10009 10010 BinOp = (ISD::NodeType)CandidateBinOp; 10011 return Op; 10012 } 10013 10014 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10015 assert(N->getNumValues() == 1 && 10016 "Can't unroll a vector with multiple results!"); 10017 10018 EVT VT = N->getValueType(0); 10019 unsigned NE = VT.getVectorNumElements(); 10020 EVT EltVT = VT.getVectorElementType(); 10021 SDLoc dl(N); 10022 10023 SmallVector<SDValue, 8> Scalars; 10024 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10025 10026 // If ResNE is 0, fully unroll the vector op. 10027 if (ResNE == 0) 10028 ResNE = NE; 10029 else if (NE > ResNE) 10030 NE = ResNE; 10031 10032 unsigned i; 10033 for (i= 0; i != NE; ++i) { 10034 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10035 SDValue Operand = N->getOperand(j); 10036 EVT OperandVT = Operand.getValueType(); 10037 if (OperandVT.isVector()) { 10038 // A vector operand; extract a single element. 10039 EVT OperandEltVT = OperandVT.getVectorElementType(); 10040 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10041 Operand, getVectorIdxConstant(i, dl)); 10042 } else { 10043 // A scalar operand; just use it as is. 10044 Operands[j] = Operand; 10045 } 10046 } 10047 10048 switch (N->getOpcode()) { 10049 default: { 10050 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10051 N->getFlags())); 10052 break; 10053 } 10054 case ISD::VSELECT: 10055 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10056 break; 10057 case ISD::SHL: 10058 case ISD::SRA: 10059 case ISD::SRL: 10060 case ISD::ROTL: 10061 case ISD::ROTR: 10062 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10063 getShiftAmountOperand(Operands[0].getValueType(), 10064 Operands[1]))); 10065 break; 10066 case ISD::SIGN_EXTEND_INREG: { 10067 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10068 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10069 Operands[0], 10070 getValueType(ExtVT))); 10071 } 10072 } 10073 } 10074 10075 for (; i < ResNE; ++i) 10076 Scalars.push_back(getUNDEF(EltVT)); 10077 10078 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10079 return getBuildVector(VecVT, dl, Scalars); 10080 } 10081 10082 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10083 SDNode *N, unsigned ResNE) { 10084 unsigned Opcode = N->getOpcode(); 10085 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10086 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10087 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10088 "Expected an overflow opcode"); 10089 10090 EVT ResVT = N->getValueType(0); 10091 EVT OvVT = N->getValueType(1); 10092 EVT ResEltVT = ResVT.getVectorElementType(); 10093 EVT OvEltVT = OvVT.getVectorElementType(); 10094 SDLoc dl(N); 10095 10096 // If ResNE is 0, fully unroll the vector op. 10097 unsigned NE = ResVT.getVectorNumElements(); 10098 if (ResNE == 0) 10099 ResNE = NE; 10100 else if (NE > ResNE) 10101 NE = ResNE; 10102 10103 SmallVector<SDValue, 8> LHSScalars; 10104 SmallVector<SDValue, 8> RHSScalars; 10105 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10106 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10107 10108 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10109 SDVTList VTs = getVTList(ResEltVT, SVT); 10110 SmallVector<SDValue, 8> ResScalars; 10111 SmallVector<SDValue, 8> OvScalars; 10112 for (unsigned i = 0; i < NE; ++i) { 10113 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10114 SDValue Ov = 10115 getSelect(dl, OvEltVT, Res.getValue(1), 10116 getBoolConstant(true, dl, OvEltVT, ResVT), 10117 getConstant(0, dl, OvEltVT)); 10118 10119 ResScalars.push_back(Res); 10120 OvScalars.push_back(Ov); 10121 } 10122 10123 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10124 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10125 10126 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10127 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10128 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10129 getBuildVector(NewOvVT, dl, OvScalars)); 10130 } 10131 10132 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10133 LoadSDNode *Base, 10134 unsigned Bytes, 10135 int Dist) const { 10136 if (LD->isVolatile() || Base->isVolatile()) 10137 return false; 10138 // TODO: probably too restrictive for atomics, revisit 10139 if (!LD->isSimple()) 10140 return false; 10141 if (LD->isIndexed() || Base->isIndexed()) 10142 return false; 10143 if (LD->getChain() != Base->getChain()) 10144 return false; 10145 EVT VT = LD->getValueType(0); 10146 if (VT.getSizeInBits() / 8 != Bytes) 10147 return false; 10148 10149 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10150 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10151 10152 int64_t Offset = 0; 10153 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10154 return (Dist * Bytes == Offset); 10155 return false; 10156 } 10157 10158 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10159 /// if it cannot be inferred. 10160 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10161 // If this is a GlobalAddress + cst, return the alignment. 10162 const GlobalValue *GV = nullptr; 10163 int64_t GVOffset = 0; 10164 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10165 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10166 KnownBits Known(PtrWidth); 10167 llvm::computeKnownBits(GV, Known, getDataLayout()); 10168 unsigned AlignBits = Known.countMinTrailingZeros(); 10169 if (AlignBits) 10170 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10171 } 10172 10173 // If this is a direct reference to a stack slot, use information about the 10174 // stack slot's alignment. 10175 int FrameIdx = INT_MIN; 10176 int64_t FrameOffset = 0; 10177 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10178 FrameIdx = FI->getIndex(); 10179 } else if (isBaseWithConstantOffset(Ptr) && 10180 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10181 // Handle FI+Cst 10182 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10183 FrameOffset = Ptr.getConstantOperandVal(1); 10184 } 10185 10186 if (FrameIdx != INT_MIN) { 10187 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10188 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10189 } 10190 10191 return None; 10192 } 10193 10194 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10195 /// which is split (or expanded) into two not necessarily identical pieces. 10196 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10197 // Currently all types are split in half. 10198 EVT LoVT, HiVT; 10199 if (!VT.isVector()) 10200 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10201 else 10202 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10203 10204 return std::make_pair(LoVT, HiVT); 10205 } 10206 10207 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10208 /// type, dependent on an enveloping VT that has been split into two identical 10209 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10210 std::pair<EVT, EVT> 10211 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10212 bool *HiIsEmpty) const { 10213 EVT EltTp = VT.getVectorElementType(); 10214 // Examples: 10215 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10216 // custom VL=9 with enveloping VL=8/8 yields 8/1 10217 // custom VL=10 with enveloping VL=8/8 yields 8/2 10218 // etc. 10219 ElementCount VTNumElts = VT.getVectorElementCount(); 10220 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10221 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10222 "Mixing fixed width and scalable vectors when enveloping a type"); 10223 EVT LoVT, HiVT; 10224 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10225 LoVT = EnvVT; 10226 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10227 *HiIsEmpty = false; 10228 } else { 10229 // Flag that hi type has zero storage size, but return split envelop type 10230 // (this would be easier if vector types with zero elements were allowed). 10231 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10232 HiVT = EnvVT; 10233 *HiIsEmpty = true; 10234 } 10235 return std::make_pair(LoVT, HiVT); 10236 } 10237 10238 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10239 /// low/high part. 10240 std::pair<SDValue, SDValue> 10241 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10242 const EVT &HiVT) { 10243 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10244 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10245 "Splitting vector with an invalid mixture of fixed and scalable " 10246 "vector types"); 10247 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10248 N.getValueType().getVectorMinNumElements() && 10249 "More vector elements requested than available!"); 10250 SDValue Lo, Hi; 10251 Lo = 10252 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10253 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10254 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10255 // IDX with the runtime scaling factor of the result vector type. For 10256 // fixed-width result vectors, that runtime scaling factor is 1. 10257 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10258 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10259 return std::make_pair(Lo, Hi); 10260 } 10261 10262 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10263 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10264 EVT VT = N.getValueType(); 10265 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10266 NextPowerOf2(VT.getVectorNumElements())); 10267 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10268 getVectorIdxConstant(0, DL)); 10269 } 10270 10271 void SelectionDAG::ExtractVectorElements(SDValue Op, 10272 SmallVectorImpl<SDValue> &Args, 10273 unsigned Start, unsigned Count, 10274 EVT EltVT) { 10275 EVT VT = Op.getValueType(); 10276 if (Count == 0) 10277 Count = VT.getVectorNumElements(); 10278 if (EltVT == EVT()) 10279 EltVT = VT.getVectorElementType(); 10280 SDLoc SL(Op); 10281 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10282 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10283 getVectorIdxConstant(i, SL))); 10284 } 10285 } 10286 10287 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10288 unsigned GlobalAddressSDNode::getAddressSpace() const { 10289 return getGlobal()->getType()->getAddressSpace(); 10290 } 10291 10292 Type *ConstantPoolSDNode::getType() const { 10293 if (isMachineConstantPoolEntry()) 10294 return Val.MachineCPVal->getType(); 10295 return Val.ConstVal->getType(); 10296 } 10297 10298 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10299 unsigned &SplatBitSize, 10300 bool &HasAnyUndefs, 10301 unsigned MinSplatBits, 10302 bool IsBigEndian) const { 10303 EVT VT = getValueType(0); 10304 assert(VT.isVector() && "Expected a vector type"); 10305 unsigned VecWidth = VT.getSizeInBits(); 10306 if (MinSplatBits > VecWidth) 10307 return false; 10308 10309 // FIXME: The widths are based on this node's type, but build vectors can 10310 // truncate their operands. 10311 SplatValue = APInt(VecWidth, 0); 10312 SplatUndef = APInt(VecWidth, 0); 10313 10314 // Get the bits. Bits with undefined values (when the corresponding element 10315 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10316 // in SplatValue. If any of the values are not constant, give up and return 10317 // false. 10318 unsigned int NumOps = getNumOperands(); 10319 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10320 unsigned EltWidth = VT.getScalarSizeInBits(); 10321 10322 for (unsigned j = 0; j < NumOps; ++j) { 10323 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10324 SDValue OpVal = getOperand(i); 10325 unsigned BitPos = j * EltWidth; 10326 10327 if (OpVal.isUndef()) 10328 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10329 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10330 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10331 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10332 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10333 else 10334 return false; 10335 } 10336 10337 // The build_vector is all constants or undefs. Find the smallest element 10338 // size that splats the vector. 10339 HasAnyUndefs = (SplatUndef != 0); 10340 10341 // FIXME: This does not work for vectors with elements less than 8 bits. 10342 while (VecWidth > 8) { 10343 unsigned HalfSize = VecWidth / 2; 10344 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10345 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10346 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10347 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10348 10349 // If the two halves do not match (ignoring undef bits), stop here. 10350 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10351 MinSplatBits > HalfSize) 10352 break; 10353 10354 SplatValue = HighValue | LowValue; 10355 SplatUndef = HighUndef & LowUndef; 10356 10357 VecWidth = HalfSize; 10358 } 10359 10360 SplatBitSize = VecWidth; 10361 return true; 10362 } 10363 10364 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10365 BitVector *UndefElements) const { 10366 unsigned NumOps = getNumOperands(); 10367 if (UndefElements) { 10368 UndefElements->clear(); 10369 UndefElements->resize(NumOps); 10370 } 10371 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10372 if (!DemandedElts) 10373 return SDValue(); 10374 SDValue Splatted; 10375 for (unsigned i = 0; i != NumOps; ++i) { 10376 if (!DemandedElts[i]) 10377 continue; 10378 SDValue Op = getOperand(i); 10379 if (Op.isUndef()) { 10380 if (UndefElements) 10381 (*UndefElements)[i] = true; 10382 } else if (!Splatted) { 10383 Splatted = Op; 10384 } else if (Splatted != Op) { 10385 return SDValue(); 10386 } 10387 } 10388 10389 if (!Splatted) { 10390 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10391 assert(getOperand(FirstDemandedIdx).isUndef() && 10392 "Can only have a splat without a constant for all undefs."); 10393 return getOperand(FirstDemandedIdx); 10394 } 10395 10396 return Splatted; 10397 } 10398 10399 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10400 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10401 return getSplatValue(DemandedElts, UndefElements); 10402 } 10403 10404 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10405 SmallVectorImpl<SDValue> &Sequence, 10406 BitVector *UndefElements) const { 10407 unsigned NumOps = getNumOperands(); 10408 Sequence.clear(); 10409 if (UndefElements) { 10410 UndefElements->clear(); 10411 UndefElements->resize(NumOps); 10412 } 10413 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10414 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10415 return false; 10416 10417 // Set the undefs even if we don't find a sequence (like getSplatValue). 10418 if (UndefElements) 10419 for (unsigned I = 0; I != NumOps; ++I) 10420 if (DemandedElts[I] && getOperand(I).isUndef()) 10421 (*UndefElements)[I] = true; 10422 10423 // Iteratively widen the sequence length looking for repetitions. 10424 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10425 Sequence.append(SeqLen, SDValue()); 10426 for (unsigned I = 0; I != NumOps; ++I) { 10427 if (!DemandedElts[I]) 10428 continue; 10429 SDValue &SeqOp = Sequence[I % SeqLen]; 10430 SDValue Op = getOperand(I); 10431 if (Op.isUndef()) { 10432 if (!SeqOp) 10433 SeqOp = Op; 10434 continue; 10435 } 10436 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10437 Sequence.clear(); 10438 break; 10439 } 10440 SeqOp = Op; 10441 } 10442 if (!Sequence.empty()) 10443 return true; 10444 } 10445 10446 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10447 return false; 10448 } 10449 10450 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10451 BitVector *UndefElements) const { 10452 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10453 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10454 } 10455 10456 ConstantSDNode * 10457 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10458 BitVector *UndefElements) const { 10459 return dyn_cast_or_null<ConstantSDNode>( 10460 getSplatValue(DemandedElts, UndefElements)); 10461 } 10462 10463 ConstantSDNode * 10464 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10465 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10466 } 10467 10468 ConstantFPSDNode * 10469 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10470 BitVector *UndefElements) const { 10471 return dyn_cast_or_null<ConstantFPSDNode>( 10472 getSplatValue(DemandedElts, UndefElements)); 10473 } 10474 10475 ConstantFPSDNode * 10476 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10477 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10478 } 10479 10480 int32_t 10481 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10482 uint32_t BitWidth) const { 10483 if (ConstantFPSDNode *CN = 10484 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10485 bool IsExact; 10486 APSInt IntVal(BitWidth); 10487 const APFloat &APF = CN->getValueAPF(); 10488 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10489 APFloat::opOK || 10490 !IsExact) 10491 return -1; 10492 10493 return IntVal.exactLogBase2(); 10494 } 10495 return -1; 10496 } 10497 10498 bool BuildVectorSDNode::isConstant() const { 10499 for (const SDValue &Op : op_values()) { 10500 unsigned Opc = Op.getOpcode(); 10501 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10502 return false; 10503 } 10504 return true; 10505 } 10506 10507 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10508 // Find the first non-undef value in the shuffle mask. 10509 unsigned i, e; 10510 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10511 /* search */; 10512 10513 // If all elements are undefined, this shuffle can be considered a splat 10514 // (although it should eventually get simplified away completely). 10515 if (i == e) 10516 return true; 10517 10518 // Make sure all remaining elements are either undef or the same as the first 10519 // non-undef value. 10520 for (int Idx = Mask[i]; i != e; ++i) 10521 if (Mask[i] >= 0 && Mask[i] != Idx) 10522 return false; 10523 return true; 10524 } 10525 10526 // Returns the SDNode if it is a constant integer BuildVector 10527 // or constant integer. 10528 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10529 if (isa<ConstantSDNode>(N)) 10530 return N.getNode(); 10531 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10532 return N.getNode(); 10533 // Treat a GlobalAddress supporting constant offset folding as a 10534 // constant integer. 10535 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10536 if (GA->getOpcode() == ISD::GlobalAddress && 10537 TLI->isOffsetFoldingLegal(GA)) 10538 return GA; 10539 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10540 isa<ConstantSDNode>(N.getOperand(0))) 10541 return N.getNode(); 10542 return nullptr; 10543 } 10544 10545 // Returns the SDNode if it is a constant float BuildVector 10546 // or constant float. 10547 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10548 if (isa<ConstantFPSDNode>(N)) 10549 return N.getNode(); 10550 10551 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10552 return N.getNode(); 10553 10554 return nullptr; 10555 } 10556 10557 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10558 assert(!Node->OperandList && "Node already has operands"); 10559 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10560 "too many operands to fit into SDNode"); 10561 SDUse *Ops = OperandRecycler.allocate( 10562 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10563 10564 bool IsDivergent = false; 10565 for (unsigned I = 0; I != Vals.size(); ++I) { 10566 Ops[I].setUser(Node); 10567 Ops[I].setInitial(Vals[I]); 10568 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10569 IsDivergent |= Ops[I].getNode()->isDivergent(); 10570 } 10571 Node->NumOperands = Vals.size(); 10572 Node->OperandList = Ops; 10573 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10574 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10575 Node->SDNodeBits.IsDivergent = IsDivergent; 10576 } 10577 checkForCycles(Node); 10578 } 10579 10580 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10581 SmallVectorImpl<SDValue> &Vals) { 10582 size_t Limit = SDNode::getMaxNumOperands(); 10583 while (Vals.size() > Limit) { 10584 unsigned SliceIdx = Vals.size() - Limit; 10585 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10586 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10587 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10588 Vals.emplace_back(NewTF); 10589 } 10590 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10591 } 10592 10593 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10594 EVT VT, SDNodeFlags Flags) { 10595 switch (Opcode) { 10596 default: 10597 return SDValue(); 10598 case ISD::ADD: 10599 case ISD::OR: 10600 case ISD::XOR: 10601 case ISD::UMAX: 10602 return getConstant(0, DL, VT); 10603 case ISD::MUL: 10604 return getConstant(1, DL, VT); 10605 case ISD::AND: 10606 case ISD::UMIN: 10607 return getAllOnesConstant(DL, VT); 10608 case ISD::SMAX: 10609 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10610 case ISD::SMIN: 10611 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10612 case ISD::FADD: 10613 return getConstantFP(-0.0, DL, VT); 10614 case ISD::FMUL: 10615 return getConstantFP(1.0, DL, VT); 10616 case ISD::FMINNUM: 10617 case ISD::FMAXNUM: { 10618 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10619 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10620 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10621 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10622 APFloat::getLargest(Semantics); 10623 if (Opcode == ISD::FMAXNUM) 10624 NeutralAF.changeSign(); 10625 10626 return getConstantFP(NeutralAF, DL, VT); 10627 } 10628 } 10629 } 10630 10631 #ifndef NDEBUG 10632 static void checkForCyclesHelper(const SDNode *N, 10633 SmallPtrSetImpl<const SDNode*> &Visited, 10634 SmallPtrSetImpl<const SDNode*> &Checked, 10635 const llvm::SelectionDAG *DAG) { 10636 // If this node has already been checked, don't check it again. 10637 if (Checked.count(N)) 10638 return; 10639 10640 // If a node has already been visited on this depth-first walk, reject it as 10641 // a cycle. 10642 if (!Visited.insert(N).second) { 10643 errs() << "Detected cycle in SelectionDAG\n"; 10644 dbgs() << "Offending node:\n"; 10645 N->dumprFull(DAG); dbgs() << "\n"; 10646 abort(); 10647 } 10648 10649 for (const SDValue &Op : N->op_values()) 10650 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10651 10652 Checked.insert(N); 10653 Visited.erase(N); 10654 } 10655 #endif 10656 10657 void llvm::checkForCycles(const llvm::SDNode *N, 10658 const llvm::SelectionDAG *DAG, 10659 bool force) { 10660 #ifndef NDEBUG 10661 bool check = force; 10662 #ifdef EXPENSIVE_CHECKS 10663 check = true; 10664 #endif // EXPENSIVE_CHECKS 10665 if (check) { 10666 assert(N && "Checking nonexistent SDNode"); 10667 SmallPtrSet<const SDNode*, 32> visited; 10668 SmallPtrSet<const SDNode*, 32> checked; 10669 checkForCyclesHelper(N, visited, checked, DAG); 10670 } 10671 #endif // !NDEBUG 10672 } 10673 10674 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10675 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10676 } 10677