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 } 150 151 auto *BV = dyn_cast<BuildVectorSDNode>(N); 152 if (!BV) 153 return false; 154 155 APInt SplatUndef; 156 unsigned SplatBitSize; 157 bool HasUndefs; 158 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 159 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 160 EltSize) && 161 EltSize == SplatBitSize; 162 } 163 164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 165 // specializations of the more general isConstantSplatVector()? 166 167 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 168 // Look through a bit convert. 169 while (N->getOpcode() == ISD::BITCAST) 170 N = N->getOperand(0).getNode(); 171 172 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 173 APInt SplatVal; 174 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue(); 175 } 176 177 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 178 179 unsigned i = 0, e = N->getNumOperands(); 180 181 // Skip over all of the undef values. 182 while (i != e && N->getOperand(i).isUndef()) 183 ++i; 184 185 // Do not accept an all-undef vector. 186 if (i == e) return false; 187 188 // Do not accept build_vectors that aren't all constants or which have non-~0 189 // elements. We have to be a bit careful here, as the type of the constant 190 // may not be the same as the type of the vector elements due to type 191 // legalization (the elements are promoted to a legal type for the target and 192 // a vector of a type may be legal when the base element type is not). 193 // We only want to check enough bits to cover the vector elements, because 194 // we care if the resultant vector is all ones, not whether the individual 195 // constants are. 196 SDValue NotZero = N->getOperand(i); 197 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 198 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 199 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 200 return false; 201 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 202 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 203 return false; 204 } else 205 return false; 206 207 // Okay, we have at least one ~0 value, check to see if the rest match or are 208 // undefs. Even with the above element type twiddling, this should be OK, as 209 // the same type legalization should have applied to all the elements. 210 for (++i; i != e; ++i) 211 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 212 return false; 213 return true; 214 } 215 216 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 217 // Look through a bit convert. 218 while (N->getOpcode() == ISD::BITCAST) 219 N = N->getOperand(0).getNode(); 220 221 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 222 APInt SplatVal; 223 return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue(); 224 } 225 226 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 227 228 bool IsAllUndef = true; 229 for (const SDValue &Op : N->op_values()) { 230 if (Op.isUndef()) 231 continue; 232 IsAllUndef = false; 233 // Do not accept build_vectors that aren't all constants or which have non-0 234 // elements. We have to be a bit careful here, as the type of the constant 235 // may not be the same as the type of the vector elements due to type 236 // legalization (the elements are promoted to a legal type for the target 237 // and a vector of a type may be legal when the base element type is not). 238 // We only want to check enough bits to cover the vector elements, because 239 // we care if the resultant vector is all zeros, not whether the individual 240 // constants are. 241 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 242 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 243 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 244 return false; 245 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 246 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 247 return false; 248 } else 249 return false; 250 } 251 252 // Do not accept an all-undef vector. 253 if (IsAllUndef) 254 return false; 255 return true; 256 } 257 258 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 259 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 260 } 261 262 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 263 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 264 } 265 266 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 267 if (N->getOpcode() != ISD::BUILD_VECTOR) 268 return false; 269 270 for (const SDValue &Op : N->op_values()) { 271 if (Op.isUndef()) 272 continue; 273 if (!isa<ConstantSDNode>(Op)) 274 return false; 275 } 276 return true; 277 } 278 279 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 280 if (N->getOpcode() != ISD::BUILD_VECTOR) 281 return false; 282 283 for (const SDValue &Op : N->op_values()) { 284 if (Op.isUndef()) 285 continue; 286 if (!isa<ConstantFPSDNode>(Op)) 287 return false; 288 } 289 return true; 290 } 291 292 bool ISD::allOperandsUndef(const SDNode *N) { 293 // Return false if the node has no operands. 294 // This is "logically inconsistent" with the definition of "all" but 295 // is probably the desired behavior. 296 if (N->getNumOperands() == 0) 297 return false; 298 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 299 } 300 301 bool ISD::matchUnaryPredicate(SDValue Op, 302 std::function<bool(ConstantSDNode *)> Match, 303 bool AllowUndefs) { 304 // FIXME: Add support for scalar UNDEF cases? 305 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 306 return Match(Cst); 307 308 // FIXME: Add support for vector UNDEF cases? 309 if (ISD::BUILD_VECTOR != Op.getOpcode() && 310 ISD::SPLAT_VECTOR != Op.getOpcode()) 311 return false; 312 313 EVT SVT = Op.getValueType().getScalarType(); 314 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 315 if (AllowUndefs && Op.getOperand(i).isUndef()) { 316 if (!Match(nullptr)) 317 return false; 318 continue; 319 } 320 321 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 322 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 323 return false; 324 } 325 return true; 326 } 327 328 bool ISD::matchBinaryPredicate( 329 SDValue LHS, SDValue RHS, 330 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 331 bool AllowUndefs, bool AllowTypeMismatch) { 332 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 333 return false; 334 335 // TODO: Add support for scalar UNDEF cases? 336 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 337 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 338 return Match(LHSCst, RHSCst); 339 340 // TODO: Add support for vector UNDEF cases? 341 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 342 ISD::BUILD_VECTOR != RHS.getOpcode()) 343 return false; 344 345 EVT SVT = LHS.getValueType().getScalarType(); 346 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 347 SDValue LHSOp = LHS.getOperand(i); 348 SDValue RHSOp = RHS.getOperand(i); 349 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 350 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 351 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 352 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 353 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 354 return false; 355 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 356 LHSOp.getValueType() != RHSOp.getValueType())) 357 return false; 358 if (!Match(LHSCst, RHSCst)) 359 return false; 360 } 361 return true; 362 } 363 364 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 365 switch (VecReduceOpcode) { 366 default: 367 llvm_unreachable("Expected VECREDUCE opcode"); 368 case ISD::VECREDUCE_FADD: 369 case ISD::VECREDUCE_SEQ_FADD: 370 return ISD::FADD; 371 case ISD::VECREDUCE_FMUL: 372 case ISD::VECREDUCE_SEQ_FMUL: 373 return ISD::FMUL; 374 case ISD::VECREDUCE_ADD: 375 return ISD::ADD; 376 case ISD::VECREDUCE_MUL: 377 return ISD::MUL; 378 case ISD::VECREDUCE_AND: 379 return ISD::AND; 380 case ISD::VECREDUCE_OR: 381 return ISD::OR; 382 case ISD::VECREDUCE_XOR: 383 return ISD::XOR; 384 case ISD::VECREDUCE_SMAX: 385 return ISD::SMAX; 386 case ISD::VECREDUCE_SMIN: 387 return ISD::SMIN; 388 case ISD::VECREDUCE_UMAX: 389 return ISD::UMAX; 390 case ISD::VECREDUCE_UMIN: 391 return ISD::UMIN; 392 case ISD::VECREDUCE_FMAX: 393 return ISD::FMAXNUM; 394 case ISD::VECREDUCE_FMIN: 395 return ISD::FMINNUM; 396 } 397 } 398 399 bool ISD::isVPOpcode(unsigned Opcode) { 400 switch (Opcode) { 401 default: 402 return false; 403 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 404 case ISD::SDOPC: \ 405 return true; 406 #include "llvm/IR/VPIntrinsics.def" 407 } 408 } 409 410 /// The operand position of the vector mask. 411 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 412 switch (Opcode) { 413 default: 414 return None; 415 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 416 case ISD::SDOPC: \ 417 return MASKPOS; 418 #include "llvm/IR/VPIntrinsics.def" 419 } 420 } 421 422 /// The operand position of the explicit vector length parameter. 423 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 424 switch (Opcode) { 425 default: 426 return None; 427 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 428 case ISD::SDOPC: \ 429 return EVLPOS; 430 #include "llvm/IR/VPIntrinsics.def" 431 } 432 } 433 434 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 435 switch (ExtType) { 436 case ISD::EXTLOAD: 437 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 438 case ISD::SEXTLOAD: 439 return ISD::SIGN_EXTEND; 440 case ISD::ZEXTLOAD: 441 return ISD::ZERO_EXTEND; 442 default: 443 break; 444 } 445 446 llvm_unreachable("Invalid LoadExtType"); 447 } 448 449 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 450 // To perform this operation, we just need to swap the L and G bits of the 451 // operation. 452 unsigned OldL = (Operation >> 2) & 1; 453 unsigned OldG = (Operation >> 1) & 1; 454 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 455 (OldL << 1) | // New G bit 456 (OldG << 2)); // New L bit. 457 } 458 459 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 460 unsigned Operation = Op; 461 if (isIntegerLike) 462 Operation ^= 7; // Flip L, G, E bits, but not U. 463 else 464 Operation ^= 15; // Flip all of the condition bits. 465 466 if (Operation > ISD::SETTRUE2) 467 Operation &= ~8; // Don't let N and U bits get set. 468 469 return ISD::CondCode(Operation); 470 } 471 472 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 473 return getSetCCInverseImpl(Op, Type.isInteger()); 474 } 475 476 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 477 bool isIntegerLike) { 478 return getSetCCInverseImpl(Op, isIntegerLike); 479 } 480 481 /// For an integer comparison, return 1 if the comparison is a signed operation 482 /// and 2 if the result is an unsigned comparison. Return zero if the operation 483 /// does not depend on the sign of the input (setne and seteq). 484 static int isSignedOp(ISD::CondCode Opcode) { 485 switch (Opcode) { 486 default: llvm_unreachable("Illegal integer setcc operation!"); 487 case ISD::SETEQ: 488 case ISD::SETNE: return 0; 489 case ISD::SETLT: 490 case ISD::SETLE: 491 case ISD::SETGT: 492 case ISD::SETGE: return 1; 493 case ISD::SETULT: 494 case ISD::SETULE: 495 case ISD::SETUGT: 496 case ISD::SETUGE: return 2; 497 } 498 } 499 500 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 501 EVT Type) { 502 bool IsInteger = Type.isInteger(); 503 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 504 // Cannot fold a signed integer setcc with an unsigned integer setcc. 505 return ISD::SETCC_INVALID; 506 507 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 508 509 // If the N and U bits get set, then the resultant comparison DOES suddenly 510 // care about orderedness, and it is true when ordered. 511 if (Op > ISD::SETTRUE2) 512 Op &= ~16; // Clear the U bit if the N bit is set. 513 514 // Canonicalize illegal integer setcc's. 515 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 516 Op = ISD::SETNE; 517 518 return ISD::CondCode(Op); 519 } 520 521 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 522 EVT Type) { 523 bool IsInteger = Type.isInteger(); 524 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 525 // Cannot fold a signed setcc with an unsigned setcc. 526 return ISD::SETCC_INVALID; 527 528 // Combine all of the condition bits. 529 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 530 531 // Canonicalize illegal integer setcc's. 532 if (IsInteger) { 533 switch (Result) { 534 default: break; 535 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 536 case ISD::SETOEQ: // SETEQ & SETU[LG]E 537 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 538 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 539 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 540 } 541 } 542 543 return Result; 544 } 545 546 //===----------------------------------------------------------------------===// 547 // SDNode Profile Support 548 //===----------------------------------------------------------------------===// 549 550 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 551 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 552 ID.AddInteger(OpC); 553 } 554 555 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 556 /// solely with their pointer. 557 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 558 ID.AddPointer(VTList.VTs); 559 } 560 561 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 562 static void AddNodeIDOperands(FoldingSetNodeID &ID, 563 ArrayRef<SDValue> Ops) { 564 for (auto& Op : Ops) { 565 ID.AddPointer(Op.getNode()); 566 ID.AddInteger(Op.getResNo()); 567 } 568 } 569 570 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 571 static void AddNodeIDOperands(FoldingSetNodeID &ID, 572 ArrayRef<SDUse> Ops) { 573 for (auto& Op : Ops) { 574 ID.AddPointer(Op.getNode()); 575 ID.AddInteger(Op.getResNo()); 576 } 577 } 578 579 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 580 SDVTList VTList, ArrayRef<SDValue> OpList) { 581 AddNodeIDOpcode(ID, OpC); 582 AddNodeIDValueTypes(ID, VTList); 583 AddNodeIDOperands(ID, OpList); 584 } 585 586 /// If this is an SDNode with special info, add this info to the NodeID data. 587 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 588 switch (N->getOpcode()) { 589 case ISD::TargetExternalSymbol: 590 case ISD::ExternalSymbol: 591 case ISD::MCSymbol: 592 llvm_unreachable("Should only be used on nodes with operands"); 593 default: break; // Normal nodes don't need extra info. 594 case ISD::TargetConstant: 595 case ISD::Constant: { 596 const ConstantSDNode *C = cast<ConstantSDNode>(N); 597 ID.AddPointer(C->getConstantIntValue()); 598 ID.AddBoolean(C->isOpaque()); 599 break; 600 } 601 case ISD::TargetConstantFP: 602 case ISD::ConstantFP: 603 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 604 break; 605 case ISD::TargetGlobalAddress: 606 case ISD::GlobalAddress: 607 case ISD::TargetGlobalTLSAddress: 608 case ISD::GlobalTLSAddress: { 609 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 610 ID.AddPointer(GA->getGlobal()); 611 ID.AddInteger(GA->getOffset()); 612 ID.AddInteger(GA->getTargetFlags()); 613 break; 614 } 615 case ISD::BasicBlock: 616 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 617 break; 618 case ISD::Register: 619 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 620 break; 621 case ISD::RegisterMask: 622 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 623 break; 624 case ISD::SRCVALUE: 625 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 626 break; 627 case ISD::FrameIndex: 628 case ISD::TargetFrameIndex: 629 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 630 break; 631 case ISD::LIFETIME_START: 632 case ISD::LIFETIME_END: 633 if (cast<LifetimeSDNode>(N)->hasOffset()) { 634 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 635 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 636 } 637 break; 638 case ISD::PSEUDO_PROBE: 639 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 640 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 641 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 642 break; 643 case ISD::JumpTable: 644 case ISD::TargetJumpTable: 645 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 646 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 647 break; 648 case ISD::ConstantPool: 649 case ISD::TargetConstantPool: { 650 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 651 ID.AddInteger(CP->getAlign().value()); 652 ID.AddInteger(CP->getOffset()); 653 if (CP->isMachineConstantPoolEntry()) 654 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 655 else 656 ID.AddPointer(CP->getConstVal()); 657 ID.AddInteger(CP->getTargetFlags()); 658 break; 659 } 660 case ISD::TargetIndex: { 661 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 662 ID.AddInteger(TI->getIndex()); 663 ID.AddInteger(TI->getOffset()); 664 ID.AddInteger(TI->getTargetFlags()); 665 break; 666 } 667 case ISD::LOAD: { 668 const LoadSDNode *LD = cast<LoadSDNode>(N); 669 ID.AddInteger(LD->getMemoryVT().getRawBits()); 670 ID.AddInteger(LD->getRawSubclassData()); 671 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 672 break; 673 } 674 case ISD::STORE: { 675 const StoreSDNode *ST = cast<StoreSDNode>(N); 676 ID.AddInteger(ST->getMemoryVT().getRawBits()); 677 ID.AddInteger(ST->getRawSubclassData()); 678 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 679 break; 680 } 681 case ISD::MLOAD: { 682 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 683 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 684 ID.AddInteger(MLD->getRawSubclassData()); 685 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 686 break; 687 } 688 case ISD::MSTORE: { 689 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 690 ID.AddInteger(MST->getMemoryVT().getRawBits()); 691 ID.AddInteger(MST->getRawSubclassData()); 692 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 693 break; 694 } 695 case ISD::MGATHER: { 696 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 697 ID.AddInteger(MG->getMemoryVT().getRawBits()); 698 ID.AddInteger(MG->getRawSubclassData()); 699 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 700 break; 701 } 702 case ISD::MSCATTER: { 703 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 704 ID.AddInteger(MS->getMemoryVT().getRawBits()); 705 ID.AddInteger(MS->getRawSubclassData()); 706 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 707 break; 708 } 709 case ISD::ATOMIC_CMP_SWAP: 710 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 711 case ISD::ATOMIC_SWAP: 712 case ISD::ATOMIC_LOAD_ADD: 713 case ISD::ATOMIC_LOAD_SUB: 714 case ISD::ATOMIC_LOAD_AND: 715 case ISD::ATOMIC_LOAD_CLR: 716 case ISD::ATOMIC_LOAD_OR: 717 case ISD::ATOMIC_LOAD_XOR: 718 case ISD::ATOMIC_LOAD_NAND: 719 case ISD::ATOMIC_LOAD_MIN: 720 case ISD::ATOMIC_LOAD_MAX: 721 case ISD::ATOMIC_LOAD_UMIN: 722 case ISD::ATOMIC_LOAD_UMAX: 723 case ISD::ATOMIC_LOAD: 724 case ISD::ATOMIC_STORE: { 725 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 726 ID.AddInteger(AT->getMemoryVT().getRawBits()); 727 ID.AddInteger(AT->getRawSubclassData()); 728 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 729 break; 730 } 731 case ISD::PREFETCH: { 732 const MemSDNode *PF = cast<MemSDNode>(N); 733 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 734 break; 735 } 736 case ISD::VECTOR_SHUFFLE: { 737 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 738 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 739 i != e; ++i) 740 ID.AddInteger(SVN->getMaskElt(i)); 741 break; 742 } 743 case ISD::TargetBlockAddress: 744 case ISD::BlockAddress: { 745 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 746 ID.AddPointer(BA->getBlockAddress()); 747 ID.AddInteger(BA->getOffset()); 748 ID.AddInteger(BA->getTargetFlags()); 749 break; 750 } 751 } // end switch (N->getOpcode()) 752 753 // Target specific memory nodes could also have address spaces to check. 754 if (N->isTargetMemoryOpcode()) 755 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 756 } 757 758 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 759 /// data. 760 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 761 AddNodeIDOpcode(ID, N->getOpcode()); 762 // Add the return value info. 763 AddNodeIDValueTypes(ID, N->getVTList()); 764 // Add the operand info. 765 AddNodeIDOperands(ID, N->ops()); 766 767 // Handle SDNode leafs with special info. 768 AddNodeIDCustom(ID, N); 769 } 770 771 //===----------------------------------------------------------------------===// 772 // SelectionDAG Class 773 //===----------------------------------------------------------------------===// 774 775 /// doNotCSE - Return true if CSE should not be performed for this node. 776 static bool doNotCSE(SDNode *N) { 777 if (N->getValueType(0) == MVT::Glue) 778 return true; // Never CSE anything that produces a flag. 779 780 switch (N->getOpcode()) { 781 default: break; 782 case ISD::HANDLENODE: 783 case ISD::EH_LABEL: 784 return true; // Never CSE these nodes. 785 } 786 787 // Check that remaining values produced are not flags. 788 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 789 if (N->getValueType(i) == MVT::Glue) 790 return true; // Never CSE anything that produces a flag. 791 792 return false; 793 } 794 795 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 796 /// SelectionDAG. 797 void SelectionDAG::RemoveDeadNodes() { 798 // Create a dummy node (which is not added to allnodes), that adds a reference 799 // to the root node, preventing it from being deleted. 800 HandleSDNode Dummy(getRoot()); 801 802 SmallVector<SDNode*, 128> DeadNodes; 803 804 // Add all obviously-dead nodes to the DeadNodes worklist. 805 for (SDNode &Node : allnodes()) 806 if (Node.use_empty()) 807 DeadNodes.push_back(&Node); 808 809 RemoveDeadNodes(DeadNodes); 810 811 // If the root changed (e.g. it was a dead load, update the root). 812 setRoot(Dummy.getValue()); 813 } 814 815 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 816 /// given list, and any nodes that become unreachable as a result. 817 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 818 819 // Process the worklist, deleting the nodes and adding their uses to the 820 // worklist. 821 while (!DeadNodes.empty()) { 822 SDNode *N = DeadNodes.pop_back_val(); 823 // Skip to next node if we've already managed to delete the node. This could 824 // happen if replacing a node causes a node previously added to the node to 825 // be deleted. 826 if (N->getOpcode() == ISD::DELETED_NODE) 827 continue; 828 829 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 830 DUL->NodeDeleted(N, nullptr); 831 832 // Take the node out of the appropriate CSE map. 833 RemoveNodeFromCSEMaps(N); 834 835 // Next, brutally remove the operand list. This is safe to do, as there are 836 // no cycles in the graph. 837 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 838 SDUse &Use = *I++; 839 SDNode *Operand = Use.getNode(); 840 Use.set(SDValue()); 841 842 // Now that we removed this operand, see if there are no uses of it left. 843 if (Operand->use_empty()) 844 DeadNodes.push_back(Operand); 845 } 846 847 DeallocateNode(N); 848 } 849 } 850 851 void SelectionDAG::RemoveDeadNode(SDNode *N){ 852 SmallVector<SDNode*, 16> DeadNodes(1, N); 853 854 // Create a dummy node that adds a reference to the root node, preventing 855 // it from being deleted. (This matters if the root is an operand of the 856 // dead node.) 857 HandleSDNode Dummy(getRoot()); 858 859 RemoveDeadNodes(DeadNodes); 860 } 861 862 void SelectionDAG::DeleteNode(SDNode *N) { 863 // First take this out of the appropriate CSE map. 864 RemoveNodeFromCSEMaps(N); 865 866 // Finally, remove uses due to operands of this node, remove from the 867 // AllNodes list, and delete the node. 868 DeleteNodeNotInCSEMaps(N); 869 } 870 871 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 872 assert(N->getIterator() != AllNodes.begin() && 873 "Cannot delete the entry node!"); 874 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 875 876 // Drop all of the operands and decrement used node's use counts. 877 N->DropOperands(); 878 879 DeallocateNode(N); 880 } 881 882 void SDDbgInfo::erase(const SDNode *Node) { 883 DbgValMapType::iterator I = DbgValMap.find(Node); 884 if (I == DbgValMap.end()) 885 return; 886 for (auto &Val: I->second) 887 Val->setIsInvalidated(); 888 DbgValMap.erase(I); 889 } 890 891 void SelectionDAG::DeallocateNode(SDNode *N) { 892 // If we have operands, deallocate them. 893 removeOperands(N); 894 895 NodeAllocator.Deallocate(AllNodes.remove(N)); 896 897 // Set the opcode to DELETED_NODE to help catch bugs when node 898 // memory is reallocated. 899 // FIXME: There are places in SDag that have grown a dependency on the opcode 900 // value in the released node. 901 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 902 N->NodeType = ISD::DELETED_NODE; 903 904 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 905 // them and forget about that node. 906 DbgInfo->erase(N); 907 } 908 909 #ifndef NDEBUG 910 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 911 static void VerifySDNode(SDNode *N) { 912 switch (N->getOpcode()) { 913 default: 914 break; 915 case ISD::BUILD_PAIR: { 916 EVT VT = N->getValueType(0); 917 assert(N->getNumValues() == 1 && "Too many results!"); 918 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 919 "Wrong return type!"); 920 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 921 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 922 "Mismatched operand types!"); 923 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 924 "Wrong operand type!"); 925 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 926 "Wrong return type size"); 927 break; 928 } 929 case ISD::BUILD_VECTOR: { 930 assert(N->getNumValues() == 1 && "Too many results!"); 931 assert(N->getValueType(0).isVector() && "Wrong return type!"); 932 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 933 "Wrong number of operands!"); 934 EVT EltVT = N->getValueType(0).getVectorElementType(); 935 for (const SDUse &Op : N->ops()) { 936 assert((Op.getValueType() == EltVT || 937 (EltVT.isInteger() && Op.getValueType().isInteger() && 938 EltVT.bitsLE(Op.getValueType()))) && 939 "Wrong operand type!"); 940 assert(Op.getValueType() == N->getOperand(0).getValueType() && 941 "Operands must all have the same type"); 942 } 943 break; 944 } 945 } 946 } 947 #endif // NDEBUG 948 949 /// Insert a newly allocated node into the DAG. 950 /// 951 /// Handles insertion into the all nodes list and CSE map, as well as 952 /// verification and other common operations when a new node is allocated. 953 void SelectionDAG::InsertNode(SDNode *N) { 954 AllNodes.push_back(N); 955 #ifndef NDEBUG 956 N->PersistentId = NextPersistentId++; 957 VerifySDNode(N); 958 #endif 959 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 960 DUL->NodeInserted(N); 961 } 962 963 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 964 /// correspond to it. This is useful when we're about to delete or repurpose 965 /// the node. We don't want future request for structurally identical nodes 966 /// to return N anymore. 967 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 968 bool Erased = false; 969 switch (N->getOpcode()) { 970 case ISD::HANDLENODE: return false; // noop. 971 case ISD::CONDCODE: 972 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 973 "Cond code doesn't exist!"); 974 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 975 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 976 break; 977 case ISD::ExternalSymbol: 978 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 979 break; 980 case ISD::TargetExternalSymbol: { 981 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 982 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 983 ESN->getSymbol(), ESN->getTargetFlags())); 984 break; 985 } 986 case ISD::MCSymbol: { 987 auto *MCSN = cast<MCSymbolSDNode>(N); 988 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 989 break; 990 } 991 case ISD::VALUETYPE: { 992 EVT VT = cast<VTSDNode>(N)->getVT(); 993 if (VT.isExtended()) { 994 Erased = ExtendedValueTypeNodes.erase(VT); 995 } else { 996 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 997 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 998 } 999 break; 1000 } 1001 default: 1002 // Remove it from the CSE Map. 1003 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1004 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1005 Erased = CSEMap.RemoveNode(N); 1006 break; 1007 } 1008 #ifndef NDEBUG 1009 // Verify that the node was actually in one of the CSE maps, unless it has a 1010 // flag result (which cannot be CSE'd) or is one of the special cases that are 1011 // not subject to CSE. 1012 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1013 !N->isMachineOpcode() && !doNotCSE(N)) { 1014 N->dump(this); 1015 dbgs() << "\n"; 1016 llvm_unreachable("Node is not in map!"); 1017 } 1018 #endif 1019 return Erased; 1020 } 1021 1022 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1023 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1024 /// node already exists, in which case transfer all its users to the existing 1025 /// node. This transfer can potentially trigger recursive merging. 1026 void 1027 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1028 // For node types that aren't CSE'd, just act as if no identical node 1029 // already exists. 1030 if (!doNotCSE(N)) { 1031 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1032 if (Existing != N) { 1033 // If there was already an existing matching node, use ReplaceAllUsesWith 1034 // to replace the dead one with the existing one. This can cause 1035 // recursive merging of other unrelated nodes down the line. 1036 ReplaceAllUsesWith(N, Existing); 1037 1038 // N is now dead. Inform the listeners and delete it. 1039 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1040 DUL->NodeDeleted(N, Existing); 1041 DeleteNodeNotInCSEMaps(N); 1042 return; 1043 } 1044 } 1045 1046 // If the node doesn't already exist, we updated it. Inform listeners. 1047 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1048 DUL->NodeUpdated(N); 1049 } 1050 1051 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1052 /// were replaced with those specified. If this node is never memoized, 1053 /// return null, otherwise return a pointer to the slot it would take. If a 1054 /// node already exists with these operands, the slot will be non-null. 1055 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1056 void *&InsertPos) { 1057 if (doNotCSE(N)) 1058 return nullptr; 1059 1060 SDValue Ops[] = { Op }; 1061 FoldingSetNodeID ID; 1062 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1063 AddNodeIDCustom(ID, N); 1064 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1065 if (Node) 1066 Node->intersectFlagsWith(N->getFlags()); 1067 return Node; 1068 } 1069 1070 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1071 /// were replaced with those specified. If this node is never memoized, 1072 /// return null, otherwise return a pointer to the slot it would take. If a 1073 /// node already exists with these operands, the slot will be non-null. 1074 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1075 SDValue Op1, SDValue Op2, 1076 void *&InsertPos) { 1077 if (doNotCSE(N)) 1078 return nullptr; 1079 1080 SDValue Ops[] = { Op1, Op2 }; 1081 FoldingSetNodeID ID; 1082 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1083 AddNodeIDCustom(ID, N); 1084 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1085 if (Node) 1086 Node->intersectFlagsWith(N->getFlags()); 1087 return Node; 1088 } 1089 1090 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1091 /// were replaced with those specified. If this node is never memoized, 1092 /// return null, otherwise return a pointer to the slot it would take. If a 1093 /// node already exists with these operands, the slot will be non-null. 1094 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1095 void *&InsertPos) { 1096 if (doNotCSE(N)) 1097 return nullptr; 1098 1099 FoldingSetNodeID ID; 1100 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1101 AddNodeIDCustom(ID, N); 1102 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1103 if (Node) 1104 Node->intersectFlagsWith(N->getFlags()); 1105 return Node; 1106 } 1107 1108 Align SelectionDAG::getEVTAlign(EVT VT) const { 1109 Type *Ty = VT == MVT::iPTR ? 1110 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1111 VT.getTypeForEVT(*getContext()); 1112 1113 return getDataLayout().getABITypeAlign(Ty); 1114 } 1115 1116 // EntryNode could meaningfully have debug info if we can find it... 1117 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1118 : TM(tm), OptLevel(OL), 1119 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1120 Root(getEntryNode()) { 1121 InsertNode(&EntryNode); 1122 DbgInfo = new SDDbgInfo(); 1123 } 1124 1125 void SelectionDAG::init(MachineFunction &NewMF, 1126 OptimizationRemarkEmitter &NewORE, 1127 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1128 LegacyDivergenceAnalysis * Divergence, 1129 ProfileSummaryInfo *PSIin, 1130 BlockFrequencyInfo *BFIin) { 1131 MF = &NewMF; 1132 SDAGISelPass = PassPtr; 1133 ORE = &NewORE; 1134 TLI = getSubtarget().getTargetLowering(); 1135 TSI = getSubtarget().getSelectionDAGInfo(); 1136 LibInfo = LibraryInfo; 1137 Context = &MF->getFunction().getContext(); 1138 DA = Divergence; 1139 PSI = PSIin; 1140 BFI = BFIin; 1141 } 1142 1143 SelectionDAG::~SelectionDAG() { 1144 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1145 allnodes_clear(); 1146 OperandRecycler.clear(OperandAllocator); 1147 delete DbgInfo; 1148 } 1149 1150 bool SelectionDAG::shouldOptForSize() const { 1151 return MF->getFunction().hasOptSize() || 1152 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1153 } 1154 1155 void SelectionDAG::allnodes_clear() { 1156 assert(&*AllNodes.begin() == &EntryNode); 1157 AllNodes.remove(AllNodes.begin()); 1158 while (!AllNodes.empty()) 1159 DeallocateNode(&AllNodes.front()); 1160 #ifndef NDEBUG 1161 NextPersistentId = 0; 1162 #endif 1163 } 1164 1165 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1166 void *&InsertPos) { 1167 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1168 if (N) { 1169 switch (N->getOpcode()) { 1170 default: break; 1171 case ISD::Constant: 1172 case ISD::ConstantFP: 1173 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1174 "debug location. Use another overload."); 1175 } 1176 } 1177 return N; 1178 } 1179 1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1181 const SDLoc &DL, void *&InsertPos) { 1182 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1183 if (N) { 1184 switch (N->getOpcode()) { 1185 case ISD::Constant: 1186 case ISD::ConstantFP: 1187 // Erase debug location from the node if the node is used at several 1188 // different places. Do not propagate one location to all uses as it 1189 // will cause a worse single stepping debugging experience. 1190 if (N->getDebugLoc() != DL.getDebugLoc()) 1191 N->setDebugLoc(DebugLoc()); 1192 break; 1193 default: 1194 // When the node's point of use is located earlier in the instruction 1195 // sequence than its prior point of use, update its debug info to the 1196 // earlier location. 1197 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1198 N->setDebugLoc(DL.getDebugLoc()); 1199 break; 1200 } 1201 } 1202 return N; 1203 } 1204 1205 void SelectionDAG::clear() { 1206 allnodes_clear(); 1207 OperandRecycler.clear(OperandAllocator); 1208 OperandAllocator.Reset(); 1209 CSEMap.clear(); 1210 1211 ExtendedValueTypeNodes.clear(); 1212 ExternalSymbols.clear(); 1213 TargetExternalSymbols.clear(); 1214 MCSymbols.clear(); 1215 SDCallSiteDbgInfo.clear(); 1216 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1217 static_cast<CondCodeSDNode*>(nullptr)); 1218 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1219 static_cast<SDNode*>(nullptr)); 1220 1221 EntryNode.UseList = nullptr; 1222 InsertNode(&EntryNode); 1223 Root = getEntryNode(); 1224 DbgInfo->clear(); 1225 } 1226 1227 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1228 return VT.bitsGT(Op.getValueType()) 1229 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1230 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1231 } 1232 1233 std::pair<SDValue, SDValue> 1234 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1235 const SDLoc &DL, EVT VT) { 1236 assert(!VT.bitsEq(Op.getValueType()) && 1237 "Strict no-op FP extend/round not allowed."); 1238 SDValue Res = 1239 VT.bitsGT(Op.getValueType()) 1240 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1241 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1242 {Chain, Op, getIntPtrConstant(0, DL)}); 1243 1244 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1245 } 1246 1247 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1248 return VT.bitsGT(Op.getValueType()) ? 1249 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1250 getNode(ISD::TRUNCATE, DL, VT, Op); 1251 } 1252 1253 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1254 return VT.bitsGT(Op.getValueType()) ? 1255 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1256 getNode(ISD::TRUNCATE, DL, VT, Op); 1257 } 1258 1259 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1260 return VT.bitsGT(Op.getValueType()) ? 1261 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1262 getNode(ISD::TRUNCATE, DL, VT, Op); 1263 } 1264 1265 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1266 EVT OpVT) { 1267 if (VT.bitsLE(Op.getValueType())) 1268 return getNode(ISD::TRUNCATE, SL, VT, Op); 1269 1270 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1271 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1272 } 1273 1274 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1275 EVT OpVT = Op.getValueType(); 1276 assert(VT.isInteger() && OpVT.isInteger() && 1277 "Cannot getZeroExtendInReg FP types"); 1278 assert(VT.isVector() == OpVT.isVector() && 1279 "getZeroExtendInReg type should be vector iff the operand " 1280 "type is vector!"); 1281 assert((!VT.isVector() || 1282 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1283 "Vector element counts must match in getZeroExtendInReg"); 1284 assert(VT.bitsLE(OpVT) && "Not extending!"); 1285 if (OpVT == VT) 1286 return Op; 1287 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1288 VT.getScalarSizeInBits()); 1289 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1290 } 1291 1292 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1293 // Only unsigned pointer semantics are supported right now. In the future this 1294 // might delegate to TLI to check pointer signedness. 1295 return getZExtOrTrunc(Op, DL, VT); 1296 } 1297 1298 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1299 // Only unsigned pointer semantics are supported right now. In the future this 1300 // might delegate to TLI to check pointer signedness. 1301 return getZeroExtendInReg(Op, DL, VT); 1302 } 1303 1304 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1305 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1306 EVT EltVT = VT.getScalarType(); 1307 SDValue NegOne = 1308 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1309 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1310 } 1311 1312 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1313 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1314 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1315 } 1316 1317 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1318 EVT OpVT) { 1319 if (!V) 1320 return getConstant(0, DL, VT); 1321 1322 switch (TLI->getBooleanContents(OpVT)) { 1323 case TargetLowering::ZeroOrOneBooleanContent: 1324 case TargetLowering::UndefinedBooleanContent: 1325 return getConstant(1, DL, VT); 1326 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1327 return getAllOnesConstant(DL, VT); 1328 } 1329 llvm_unreachable("Unexpected boolean content enum!"); 1330 } 1331 1332 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1333 bool isT, bool isO) { 1334 EVT EltVT = VT.getScalarType(); 1335 assert((EltVT.getSizeInBits() >= 64 || 1336 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1337 "getConstant with a uint64_t value that doesn't fit in the type!"); 1338 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1339 } 1340 1341 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1342 bool isT, bool isO) { 1343 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1344 } 1345 1346 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1347 EVT VT, bool isT, bool isO) { 1348 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1349 1350 EVT EltVT = VT.getScalarType(); 1351 const ConstantInt *Elt = &Val; 1352 1353 // In some cases the vector type is legal but the element type is illegal and 1354 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1355 // inserted value (the type does not need to match the vector element type). 1356 // Any extra bits introduced will be truncated away. 1357 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1358 TargetLowering::TypePromoteInteger) { 1359 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1360 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1361 Elt = ConstantInt::get(*getContext(), NewVal); 1362 } 1363 // In other cases the element type is illegal and needs to be expanded, for 1364 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1365 // the value into n parts and use a vector type with n-times the elements. 1366 // Then bitcast to the type requested. 1367 // Legalizing constants too early makes the DAGCombiner's job harder so we 1368 // only legalize if the DAG tells us we must produce legal types. 1369 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1370 TLI->getTypeAction(*getContext(), EltVT) == 1371 TargetLowering::TypeExpandInteger) { 1372 const APInt &NewVal = Elt->getValue(); 1373 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1374 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1375 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1376 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1377 1378 // Check the temporary vector is the correct size. If this fails then 1379 // getTypeToTransformTo() probably returned a type whose size (in bits) 1380 // isn't a power-of-2 factor of the requested type size. 1381 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1382 1383 SmallVector<SDValue, 2> EltParts; 1384 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1385 EltParts.push_back(getConstant( 1386 NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL, 1387 ViaEltVT, isT, isO)); 1388 } 1389 1390 // EltParts is currently in little endian order. If we actually want 1391 // big-endian order then reverse it now. 1392 if (getDataLayout().isBigEndian()) 1393 std::reverse(EltParts.begin(), EltParts.end()); 1394 1395 // The elements must be reversed when the element order is different 1396 // to the endianness of the elements (because the BITCAST is itself a 1397 // vector shuffle in this situation). However, we do not need any code to 1398 // perform this reversal because getConstant() is producing a vector 1399 // splat. 1400 // This situation occurs in MIPS MSA. 1401 1402 SmallVector<SDValue, 8> Ops; 1403 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1404 llvm::append_range(Ops, EltParts); 1405 1406 SDValue V = 1407 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1408 return V; 1409 } 1410 1411 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1412 "APInt size does not match type size!"); 1413 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1414 FoldingSetNodeID ID; 1415 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1416 ID.AddPointer(Elt); 1417 ID.AddBoolean(isO); 1418 void *IP = nullptr; 1419 SDNode *N = nullptr; 1420 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1421 if (!VT.isVector()) 1422 return SDValue(N, 0); 1423 1424 if (!N) { 1425 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1426 CSEMap.InsertNode(N, IP); 1427 InsertNode(N); 1428 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1429 } 1430 1431 SDValue Result(N, 0); 1432 if (VT.isScalableVector()) 1433 Result = getSplatVector(VT, DL, Result); 1434 else if (VT.isVector()) 1435 Result = getSplatBuildVector(VT, DL, Result); 1436 1437 return Result; 1438 } 1439 1440 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1441 bool isTarget) { 1442 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1443 } 1444 1445 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1446 const SDLoc &DL, bool LegalTypes) { 1447 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1448 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1449 return getConstant(Val, DL, ShiftVT); 1450 } 1451 1452 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1453 bool isTarget) { 1454 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1455 } 1456 1457 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1458 bool isTarget) { 1459 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1460 } 1461 1462 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1463 EVT VT, bool isTarget) { 1464 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1465 1466 EVT EltVT = VT.getScalarType(); 1467 1468 // Do the map lookup using the actual bit pattern for the floating point 1469 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1470 // we don't have issues with SNANs. 1471 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1472 FoldingSetNodeID ID; 1473 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1474 ID.AddPointer(&V); 1475 void *IP = nullptr; 1476 SDNode *N = nullptr; 1477 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1478 if (!VT.isVector()) 1479 return SDValue(N, 0); 1480 1481 if (!N) { 1482 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1483 CSEMap.InsertNode(N, IP); 1484 InsertNode(N); 1485 } 1486 1487 SDValue Result(N, 0); 1488 if (VT.isScalableVector()) 1489 Result = getSplatVector(VT, DL, Result); 1490 else if (VT.isVector()) 1491 Result = getSplatBuildVector(VT, DL, Result); 1492 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1493 return Result; 1494 } 1495 1496 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1497 bool isTarget) { 1498 EVT EltVT = VT.getScalarType(); 1499 if (EltVT == MVT::f32) 1500 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1501 else if (EltVT == MVT::f64) 1502 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1503 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1504 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1505 bool Ignored; 1506 APFloat APF = APFloat(Val); 1507 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1508 &Ignored); 1509 return getConstantFP(APF, DL, VT, isTarget); 1510 } else 1511 llvm_unreachable("Unsupported type in getConstantFP"); 1512 } 1513 1514 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1515 EVT VT, int64_t Offset, bool isTargetGA, 1516 unsigned TargetFlags) { 1517 assert((TargetFlags == 0 || isTargetGA) && 1518 "Cannot set target flags on target-independent globals"); 1519 1520 // Truncate (with sign-extension) the offset value to the pointer size. 1521 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1522 if (BitWidth < 64) 1523 Offset = SignExtend64(Offset, BitWidth); 1524 1525 unsigned Opc; 1526 if (GV->isThreadLocal()) 1527 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1528 else 1529 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1530 1531 FoldingSetNodeID ID; 1532 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1533 ID.AddPointer(GV); 1534 ID.AddInteger(Offset); 1535 ID.AddInteger(TargetFlags); 1536 void *IP = nullptr; 1537 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1538 return SDValue(E, 0); 1539 1540 auto *N = newSDNode<GlobalAddressSDNode>( 1541 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1542 CSEMap.InsertNode(N, IP); 1543 InsertNode(N); 1544 return SDValue(N, 0); 1545 } 1546 1547 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1548 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1549 FoldingSetNodeID ID; 1550 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1551 ID.AddInteger(FI); 1552 void *IP = nullptr; 1553 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1554 return SDValue(E, 0); 1555 1556 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1557 CSEMap.InsertNode(N, IP); 1558 InsertNode(N); 1559 return SDValue(N, 0); 1560 } 1561 1562 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1563 unsigned TargetFlags) { 1564 assert((TargetFlags == 0 || isTarget) && 1565 "Cannot set target flags on target-independent jump tables"); 1566 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1567 FoldingSetNodeID ID; 1568 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1569 ID.AddInteger(JTI); 1570 ID.AddInteger(TargetFlags); 1571 void *IP = nullptr; 1572 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1573 return SDValue(E, 0); 1574 1575 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1576 CSEMap.InsertNode(N, IP); 1577 InsertNode(N); 1578 return SDValue(N, 0); 1579 } 1580 1581 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1582 MaybeAlign Alignment, int Offset, 1583 bool isTarget, unsigned TargetFlags) { 1584 assert((TargetFlags == 0 || isTarget) && 1585 "Cannot set target flags on target-independent globals"); 1586 if (!Alignment) 1587 Alignment = shouldOptForSize() 1588 ? getDataLayout().getABITypeAlign(C->getType()) 1589 : getDataLayout().getPrefTypeAlign(C->getType()); 1590 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1591 FoldingSetNodeID ID; 1592 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1593 ID.AddInteger(Alignment->value()); 1594 ID.AddInteger(Offset); 1595 ID.AddPointer(C); 1596 ID.AddInteger(TargetFlags); 1597 void *IP = nullptr; 1598 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1599 return SDValue(E, 0); 1600 1601 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1602 TargetFlags); 1603 CSEMap.InsertNode(N, IP); 1604 InsertNode(N); 1605 SDValue V = SDValue(N, 0); 1606 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1607 return V; 1608 } 1609 1610 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1611 MaybeAlign Alignment, int Offset, 1612 bool isTarget, unsigned TargetFlags) { 1613 assert((TargetFlags == 0 || isTarget) && 1614 "Cannot set target flags on target-independent globals"); 1615 if (!Alignment) 1616 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1617 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1618 FoldingSetNodeID ID; 1619 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1620 ID.AddInteger(Alignment->value()); 1621 ID.AddInteger(Offset); 1622 C->addSelectionDAGCSEId(ID); 1623 ID.AddInteger(TargetFlags); 1624 void *IP = nullptr; 1625 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1626 return SDValue(E, 0); 1627 1628 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1629 TargetFlags); 1630 CSEMap.InsertNode(N, IP); 1631 InsertNode(N); 1632 return SDValue(N, 0); 1633 } 1634 1635 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1636 unsigned TargetFlags) { 1637 FoldingSetNodeID ID; 1638 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1639 ID.AddInteger(Index); 1640 ID.AddInteger(Offset); 1641 ID.AddInteger(TargetFlags); 1642 void *IP = nullptr; 1643 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1644 return SDValue(E, 0); 1645 1646 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1647 CSEMap.InsertNode(N, IP); 1648 InsertNode(N); 1649 return SDValue(N, 0); 1650 } 1651 1652 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1653 FoldingSetNodeID ID; 1654 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1655 ID.AddPointer(MBB); 1656 void *IP = nullptr; 1657 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1658 return SDValue(E, 0); 1659 1660 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1661 CSEMap.InsertNode(N, IP); 1662 InsertNode(N); 1663 return SDValue(N, 0); 1664 } 1665 1666 SDValue SelectionDAG::getValueType(EVT VT) { 1667 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1668 ValueTypeNodes.size()) 1669 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1670 1671 SDNode *&N = VT.isExtended() ? 1672 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1673 1674 if (N) return SDValue(N, 0); 1675 N = newSDNode<VTSDNode>(VT); 1676 InsertNode(N); 1677 return SDValue(N, 0); 1678 } 1679 1680 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1681 SDNode *&N = ExternalSymbols[Sym]; 1682 if (N) return SDValue(N, 0); 1683 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1684 InsertNode(N); 1685 return SDValue(N, 0); 1686 } 1687 1688 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1689 SDNode *&N = MCSymbols[Sym]; 1690 if (N) 1691 return SDValue(N, 0); 1692 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1693 InsertNode(N); 1694 return SDValue(N, 0); 1695 } 1696 1697 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1698 unsigned TargetFlags) { 1699 SDNode *&N = 1700 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1701 if (N) return SDValue(N, 0); 1702 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1703 InsertNode(N); 1704 return SDValue(N, 0); 1705 } 1706 1707 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1708 if ((unsigned)Cond >= CondCodeNodes.size()) 1709 CondCodeNodes.resize(Cond+1); 1710 1711 if (!CondCodeNodes[Cond]) { 1712 auto *N = newSDNode<CondCodeSDNode>(Cond); 1713 CondCodeNodes[Cond] = N; 1714 InsertNode(N); 1715 } 1716 1717 return SDValue(CondCodeNodes[Cond], 0); 1718 } 1719 1720 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1721 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1722 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1723 std::swap(N1, N2); 1724 ShuffleVectorSDNode::commuteMask(M); 1725 } 1726 1727 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1728 SDValue N2, ArrayRef<int> Mask) { 1729 assert(VT.getVectorNumElements() == Mask.size() && 1730 "Must have the same number of vector elements as mask elements!"); 1731 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1732 "Invalid VECTOR_SHUFFLE"); 1733 1734 // Canonicalize shuffle undef, undef -> undef 1735 if (N1.isUndef() && N2.isUndef()) 1736 return getUNDEF(VT); 1737 1738 // Validate that all indices in Mask are within the range of the elements 1739 // input to the shuffle. 1740 int NElts = Mask.size(); 1741 assert(llvm::all_of(Mask, 1742 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1743 "Index out of range"); 1744 1745 // Copy the mask so we can do any needed cleanup. 1746 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1747 1748 // Canonicalize shuffle v, v -> v, undef 1749 if (N1 == N2) { 1750 N2 = getUNDEF(VT); 1751 for (int i = 0; i != NElts; ++i) 1752 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1753 } 1754 1755 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1756 if (N1.isUndef()) 1757 commuteShuffle(N1, N2, MaskVec); 1758 1759 if (TLI->hasVectorBlend()) { 1760 // If shuffling a splat, try to blend the splat instead. We do this here so 1761 // that even when this arises during lowering we don't have to re-handle it. 1762 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1763 BitVector UndefElements; 1764 SDValue Splat = BV->getSplatValue(&UndefElements); 1765 if (!Splat) 1766 return; 1767 1768 for (int i = 0; i < NElts; ++i) { 1769 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1770 continue; 1771 1772 // If this input comes from undef, mark it as such. 1773 if (UndefElements[MaskVec[i] - Offset]) { 1774 MaskVec[i] = -1; 1775 continue; 1776 } 1777 1778 // If we can blend a non-undef lane, use that instead. 1779 if (!UndefElements[i]) 1780 MaskVec[i] = i + Offset; 1781 } 1782 }; 1783 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1784 BlendSplat(N1BV, 0); 1785 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1786 BlendSplat(N2BV, NElts); 1787 } 1788 1789 // Canonicalize all index into lhs, -> shuffle lhs, undef 1790 // Canonicalize all index into rhs, -> shuffle rhs, undef 1791 bool AllLHS = true, AllRHS = true; 1792 bool N2Undef = N2.isUndef(); 1793 for (int i = 0; i != NElts; ++i) { 1794 if (MaskVec[i] >= NElts) { 1795 if (N2Undef) 1796 MaskVec[i] = -1; 1797 else 1798 AllLHS = false; 1799 } else if (MaskVec[i] >= 0) { 1800 AllRHS = false; 1801 } 1802 } 1803 if (AllLHS && AllRHS) 1804 return getUNDEF(VT); 1805 if (AllLHS && !N2Undef) 1806 N2 = getUNDEF(VT); 1807 if (AllRHS) { 1808 N1 = getUNDEF(VT); 1809 commuteShuffle(N1, N2, MaskVec); 1810 } 1811 // Reset our undef status after accounting for the mask. 1812 N2Undef = N2.isUndef(); 1813 // Re-check whether both sides ended up undef. 1814 if (N1.isUndef() && N2Undef) 1815 return getUNDEF(VT); 1816 1817 // If Identity shuffle return that node. 1818 bool Identity = true, AllSame = true; 1819 for (int i = 0; i != NElts; ++i) { 1820 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1821 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1822 } 1823 if (Identity && NElts) 1824 return N1; 1825 1826 // Shuffling a constant splat doesn't change the result. 1827 if (N2Undef) { 1828 SDValue V = N1; 1829 1830 // Look through any bitcasts. We check that these don't change the number 1831 // (and size) of elements and just changes their types. 1832 while (V.getOpcode() == ISD::BITCAST) 1833 V = V->getOperand(0); 1834 1835 // A splat should always show up as a build vector node. 1836 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1837 BitVector UndefElements; 1838 SDValue Splat = BV->getSplatValue(&UndefElements); 1839 // If this is a splat of an undef, shuffling it is also undef. 1840 if (Splat && Splat.isUndef()) 1841 return getUNDEF(VT); 1842 1843 bool SameNumElts = 1844 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1845 1846 // We only have a splat which can skip shuffles if there is a splatted 1847 // value and no undef lanes rearranged by the shuffle. 1848 if (Splat && UndefElements.none()) { 1849 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1850 // number of elements match or the value splatted is a zero constant. 1851 if (SameNumElts) 1852 return N1; 1853 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1854 if (C->isNullValue()) 1855 return N1; 1856 } 1857 1858 // If the shuffle itself creates a splat, build the vector directly. 1859 if (AllSame && SameNumElts) { 1860 EVT BuildVT = BV->getValueType(0); 1861 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1862 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1863 1864 // We may have jumped through bitcasts, so the type of the 1865 // BUILD_VECTOR may not match the type of the shuffle. 1866 if (BuildVT != VT) 1867 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1868 return NewBV; 1869 } 1870 } 1871 } 1872 1873 FoldingSetNodeID ID; 1874 SDValue Ops[2] = { N1, N2 }; 1875 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1876 for (int i = 0; i != NElts; ++i) 1877 ID.AddInteger(MaskVec[i]); 1878 1879 void* IP = nullptr; 1880 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1881 return SDValue(E, 0); 1882 1883 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1884 // SDNode doesn't have access to it. This memory will be "leaked" when 1885 // the node is deallocated, but recovered when the NodeAllocator is released. 1886 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1887 llvm::copy(MaskVec, MaskAlloc); 1888 1889 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1890 dl.getDebugLoc(), MaskAlloc); 1891 createOperands(N, Ops); 1892 1893 CSEMap.InsertNode(N, IP); 1894 InsertNode(N); 1895 SDValue V = SDValue(N, 0); 1896 NewSDValueDbgMsg(V, "Creating new node: ", this); 1897 return V; 1898 } 1899 1900 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1901 EVT VT = SV.getValueType(0); 1902 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1903 ShuffleVectorSDNode::commuteMask(MaskVec); 1904 1905 SDValue Op0 = SV.getOperand(0); 1906 SDValue Op1 = SV.getOperand(1); 1907 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1908 } 1909 1910 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1911 FoldingSetNodeID ID; 1912 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1913 ID.AddInteger(RegNo); 1914 void *IP = nullptr; 1915 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1916 return SDValue(E, 0); 1917 1918 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1919 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1920 CSEMap.InsertNode(N, IP); 1921 InsertNode(N); 1922 return SDValue(N, 0); 1923 } 1924 1925 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1926 FoldingSetNodeID ID; 1927 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1928 ID.AddPointer(RegMask); 1929 void *IP = nullptr; 1930 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1931 return SDValue(E, 0); 1932 1933 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1934 CSEMap.InsertNode(N, IP); 1935 InsertNode(N); 1936 return SDValue(N, 0); 1937 } 1938 1939 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1940 MCSymbol *Label) { 1941 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1942 } 1943 1944 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1945 SDValue Root, MCSymbol *Label) { 1946 FoldingSetNodeID ID; 1947 SDValue Ops[] = { Root }; 1948 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1949 ID.AddPointer(Label); 1950 void *IP = nullptr; 1951 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1952 return SDValue(E, 0); 1953 1954 auto *N = 1955 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 1956 createOperands(N, Ops); 1957 1958 CSEMap.InsertNode(N, IP); 1959 InsertNode(N); 1960 return SDValue(N, 0); 1961 } 1962 1963 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1964 int64_t Offset, bool isTarget, 1965 unsigned TargetFlags) { 1966 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1967 1968 FoldingSetNodeID ID; 1969 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1970 ID.AddPointer(BA); 1971 ID.AddInteger(Offset); 1972 ID.AddInteger(TargetFlags); 1973 void *IP = nullptr; 1974 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1975 return SDValue(E, 0); 1976 1977 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 1978 CSEMap.InsertNode(N, IP); 1979 InsertNode(N); 1980 return SDValue(N, 0); 1981 } 1982 1983 SDValue SelectionDAG::getSrcValue(const Value *V) { 1984 FoldingSetNodeID ID; 1985 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1986 ID.AddPointer(V); 1987 1988 void *IP = nullptr; 1989 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1990 return SDValue(E, 0); 1991 1992 auto *N = newSDNode<SrcValueSDNode>(V); 1993 CSEMap.InsertNode(N, IP); 1994 InsertNode(N); 1995 return SDValue(N, 0); 1996 } 1997 1998 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1999 FoldingSetNodeID ID; 2000 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2001 ID.AddPointer(MD); 2002 2003 void *IP = nullptr; 2004 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2005 return SDValue(E, 0); 2006 2007 auto *N = newSDNode<MDNodeSDNode>(MD); 2008 CSEMap.InsertNode(N, IP); 2009 InsertNode(N); 2010 return SDValue(N, 0); 2011 } 2012 2013 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2014 if (VT == V.getValueType()) 2015 return V; 2016 2017 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2018 } 2019 2020 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2021 unsigned SrcAS, unsigned DestAS) { 2022 SDValue Ops[] = {Ptr}; 2023 FoldingSetNodeID ID; 2024 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2025 ID.AddInteger(SrcAS); 2026 ID.AddInteger(DestAS); 2027 2028 void *IP = nullptr; 2029 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2030 return SDValue(E, 0); 2031 2032 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2033 VT, SrcAS, DestAS); 2034 createOperands(N, Ops); 2035 2036 CSEMap.InsertNode(N, IP); 2037 InsertNode(N); 2038 return SDValue(N, 0); 2039 } 2040 2041 SDValue SelectionDAG::getFreeze(SDValue V) { 2042 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2043 } 2044 2045 /// getShiftAmountOperand - Return the specified value casted to 2046 /// the target's desired shift amount type. 2047 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2048 EVT OpTy = Op.getValueType(); 2049 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2050 if (OpTy == ShTy || OpTy.isVector()) return Op; 2051 2052 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2053 } 2054 2055 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2056 SDLoc dl(Node); 2057 const TargetLowering &TLI = getTargetLoweringInfo(); 2058 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2059 EVT VT = Node->getValueType(0); 2060 SDValue Tmp1 = Node->getOperand(0); 2061 SDValue Tmp2 = Node->getOperand(1); 2062 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2063 2064 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2065 Tmp2, MachinePointerInfo(V)); 2066 SDValue VAList = VAListLoad; 2067 2068 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2069 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2070 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2071 2072 VAList = 2073 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2074 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2075 } 2076 2077 // Increment the pointer, VAList, to the next vaarg 2078 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2079 getConstant(getDataLayout().getTypeAllocSize( 2080 VT.getTypeForEVT(*getContext())), 2081 dl, VAList.getValueType())); 2082 // Store the incremented VAList to the legalized pointer 2083 Tmp1 = 2084 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2085 // Load the actual argument out of the pointer VAList 2086 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2087 } 2088 2089 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2090 SDLoc dl(Node); 2091 const TargetLowering &TLI = getTargetLoweringInfo(); 2092 // This defaults to loading a pointer from the input and storing it to the 2093 // output, returning the chain. 2094 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2095 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2096 SDValue Tmp1 = 2097 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2098 Node->getOperand(2), MachinePointerInfo(VS)); 2099 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2100 MachinePointerInfo(VD)); 2101 } 2102 2103 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2104 const DataLayout &DL = getDataLayout(); 2105 Type *Ty = VT.getTypeForEVT(*getContext()); 2106 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2107 2108 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2109 return RedAlign; 2110 2111 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2112 const Align StackAlign = TFI->getStackAlign(); 2113 2114 // See if we can choose a smaller ABI alignment in cases where it's an 2115 // illegal vector type that will get broken down. 2116 if (RedAlign > StackAlign) { 2117 EVT IntermediateVT; 2118 MVT RegisterVT; 2119 unsigned NumIntermediates; 2120 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2121 NumIntermediates, RegisterVT); 2122 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2123 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2124 if (RedAlign2 < RedAlign) 2125 RedAlign = RedAlign2; 2126 } 2127 2128 return RedAlign; 2129 } 2130 2131 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2132 MachineFrameInfo &MFI = MF->getFrameInfo(); 2133 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2134 int StackID = 0; 2135 if (Bytes.isScalable()) 2136 StackID = TFI->getStackIDForScalableVectors(); 2137 // The stack id gives an indication of whether the object is scalable or 2138 // not, so it's safe to pass in the minimum size here. 2139 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2140 false, nullptr, StackID); 2141 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2142 } 2143 2144 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2145 Type *Ty = VT.getTypeForEVT(*getContext()); 2146 Align StackAlign = 2147 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2148 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2149 } 2150 2151 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2152 TypeSize VT1Size = VT1.getStoreSize(); 2153 TypeSize VT2Size = VT2.getStoreSize(); 2154 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2155 "Don't know how to choose the maximum size when creating a stack " 2156 "temporary"); 2157 TypeSize Bytes = 2158 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2159 2160 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2161 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2162 const DataLayout &DL = getDataLayout(); 2163 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2164 return CreateStackTemporary(Bytes, Align); 2165 } 2166 2167 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2168 ISD::CondCode Cond, const SDLoc &dl) { 2169 EVT OpVT = N1.getValueType(); 2170 2171 // These setcc operations always fold. 2172 switch (Cond) { 2173 default: break; 2174 case ISD::SETFALSE: 2175 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2176 case ISD::SETTRUE: 2177 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2178 2179 case ISD::SETOEQ: 2180 case ISD::SETOGT: 2181 case ISD::SETOGE: 2182 case ISD::SETOLT: 2183 case ISD::SETOLE: 2184 case ISD::SETONE: 2185 case ISD::SETO: 2186 case ISD::SETUO: 2187 case ISD::SETUEQ: 2188 case ISD::SETUNE: 2189 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2190 break; 2191 } 2192 2193 if (OpVT.isInteger()) { 2194 // For EQ and NE, we can always pick a value for the undef to make the 2195 // predicate pass or fail, so we can return undef. 2196 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2197 // icmp eq/ne X, undef -> undef. 2198 if ((N1.isUndef() || N2.isUndef()) && 2199 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2200 return getUNDEF(VT); 2201 2202 // If both operands are undef, we can return undef for int comparison. 2203 // icmp undef, undef -> undef. 2204 if (N1.isUndef() && N2.isUndef()) 2205 return getUNDEF(VT); 2206 2207 // icmp X, X -> true/false 2208 // icmp X, undef -> true/false because undef could be X. 2209 if (N1 == N2) 2210 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2211 } 2212 2213 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2214 const APInt &C2 = N2C->getAPIntValue(); 2215 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2216 const APInt &C1 = N1C->getAPIntValue(); 2217 2218 switch (Cond) { 2219 default: llvm_unreachable("Unknown integer setcc!"); 2220 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2221 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2222 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2223 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2224 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2225 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2226 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2227 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2228 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2229 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2230 } 2231 } 2232 } 2233 2234 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2235 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2236 2237 if (N1CFP && N2CFP) { 2238 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2239 switch (Cond) { 2240 default: break; 2241 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2242 return getUNDEF(VT); 2243 LLVM_FALLTHROUGH; 2244 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2245 OpVT); 2246 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2247 return getUNDEF(VT); 2248 LLVM_FALLTHROUGH; 2249 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2250 R==APFloat::cmpLessThan, dl, VT, 2251 OpVT); 2252 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2253 return getUNDEF(VT); 2254 LLVM_FALLTHROUGH; 2255 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2256 OpVT); 2257 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2258 return getUNDEF(VT); 2259 LLVM_FALLTHROUGH; 2260 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2261 VT, OpVT); 2262 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2263 return getUNDEF(VT); 2264 LLVM_FALLTHROUGH; 2265 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2266 R==APFloat::cmpEqual, dl, VT, 2267 OpVT); 2268 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2269 return getUNDEF(VT); 2270 LLVM_FALLTHROUGH; 2271 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2272 R==APFloat::cmpEqual, dl, VT, OpVT); 2273 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2274 OpVT); 2275 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2276 OpVT); 2277 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2278 R==APFloat::cmpEqual, dl, VT, 2279 OpVT); 2280 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2281 OpVT); 2282 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2283 R==APFloat::cmpLessThan, dl, VT, 2284 OpVT); 2285 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2286 R==APFloat::cmpUnordered, dl, VT, 2287 OpVT); 2288 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2289 VT, OpVT); 2290 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2291 OpVT); 2292 } 2293 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2294 // Ensure that the constant occurs on the RHS. 2295 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2296 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2297 return SDValue(); 2298 return getSetCC(dl, VT, N2, N1, SwappedCond); 2299 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2300 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2301 // If an operand is known to be a nan (or undef that could be a nan), we can 2302 // fold it. 2303 // Choosing NaN for the undef will always make unordered comparison succeed 2304 // and ordered comparison fails. 2305 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2306 switch (ISD::getUnorderedFlavor(Cond)) { 2307 default: 2308 llvm_unreachable("Unknown flavor!"); 2309 case 0: // Known false. 2310 return getBoolConstant(false, dl, VT, OpVT); 2311 case 1: // Known true. 2312 return getBoolConstant(true, dl, VT, OpVT); 2313 case 2: // Undefined. 2314 return getUNDEF(VT); 2315 } 2316 } 2317 2318 // Could not fold it. 2319 return SDValue(); 2320 } 2321 2322 /// See if the specified operand can be simplified with the knowledge that only 2323 /// the bits specified by DemandedBits are used. 2324 /// TODO: really we should be making this into the DAG equivalent of 2325 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2326 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2327 EVT VT = V.getValueType(); 2328 2329 if (VT.isScalableVector()) 2330 return SDValue(); 2331 2332 APInt DemandedElts = VT.isVector() 2333 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2334 : APInt(1, 1); 2335 return GetDemandedBits(V, DemandedBits, DemandedElts); 2336 } 2337 2338 /// See if the specified operand can be simplified with the knowledge that only 2339 /// the bits specified by DemandedBits are used in the elements specified by 2340 /// DemandedElts. 2341 /// TODO: really we should be making this into the DAG equivalent of 2342 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2343 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2344 const APInt &DemandedElts) { 2345 switch (V.getOpcode()) { 2346 default: 2347 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2348 *this, 0); 2349 case ISD::Constant: { 2350 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2351 APInt NewVal = CVal & DemandedBits; 2352 if (NewVal != CVal) 2353 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2354 break; 2355 } 2356 case ISD::SRL: 2357 // Only look at single-use SRLs. 2358 if (!V.getNode()->hasOneUse()) 2359 break; 2360 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2361 // See if we can recursively simplify the LHS. 2362 unsigned Amt = RHSC->getZExtValue(); 2363 2364 // Watch out for shift count overflow though. 2365 if (Amt >= DemandedBits.getBitWidth()) 2366 break; 2367 APInt SrcDemandedBits = DemandedBits << Amt; 2368 if (SDValue SimplifyLHS = 2369 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2370 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2371 V.getOperand(1)); 2372 } 2373 break; 2374 } 2375 return SDValue(); 2376 } 2377 2378 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2379 /// use this predicate to simplify operations downstream. 2380 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2381 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2382 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2383 } 2384 2385 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2386 /// this predicate to simplify operations downstream. Mask is known to be zero 2387 /// for bits that V cannot have. 2388 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2389 unsigned Depth) const { 2390 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2391 } 2392 2393 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2394 /// DemandedElts. We use this predicate to simplify operations downstream. 2395 /// Mask is known to be zero for bits that V cannot have. 2396 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2397 const APInt &DemandedElts, 2398 unsigned Depth) const { 2399 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2400 } 2401 2402 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2403 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2404 unsigned Depth) const { 2405 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2406 } 2407 2408 /// isSplatValue - Return true if the vector V has the same value 2409 /// across all DemandedElts. For scalable vectors it does not make 2410 /// sense to specify which elements are demanded or undefined, therefore 2411 /// they are simply ignored. 2412 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2413 APInt &UndefElts, unsigned Depth) { 2414 EVT VT = V.getValueType(); 2415 assert(VT.isVector() && "Vector type expected"); 2416 2417 if (!VT.isScalableVector() && !DemandedElts) 2418 return false; // No demanded elts, better to assume we don't know anything. 2419 2420 if (Depth >= MaxRecursionDepth) 2421 return false; // Limit search depth. 2422 2423 // Deal with some common cases here that work for both fixed and scalable 2424 // vector types. 2425 switch (V.getOpcode()) { 2426 case ISD::SPLAT_VECTOR: 2427 UndefElts = V.getOperand(0).isUndef() 2428 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2429 : APInt(DemandedElts.getBitWidth(), 0); 2430 return true; 2431 case ISD::ADD: 2432 case ISD::SUB: 2433 case ISD::AND: 2434 case ISD::XOR: 2435 case ISD::OR: { 2436 APInt UndefLHS, UndefRHS; 2437 SDValue LHS = V.getOperand(0); 2438 SDValue RHS = V.getOperand(1); 2439 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2440 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2441 UndefElts = UndefLHS | UndefRHS; 2442 return true; 2443 } 2444 break; 2445 } 2446 case ISD::TRUNCATE: 2447 case ISD::SIGN_EXTEND: 2448 case ISD::ZERO_EXTEND: 2449 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2450 } 2451 2452 // We don't support other cases than those above for scalable vectors at 2453 // the moment. 2454 if (VT.isScalableVector()) 2455 return false; 2456 2457 unsigned NumElts = VT.getVectorNumElements(); 2458 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2459 UndefElts = APInt::getNullValue(NumElts); 2460 2461 switch (V.getOpcode()) { 2462 case ISD::BUILD_VECTOR: { 2463 SDValue Scl; 2464 for (unsigned i = 0; i != NumElts; ++i) { 2465 SDValue Op = V.getOperand(i); 2466 if (Op.isUndef()) { 2467 UndefElts.setBit(i); 2468 continue; 2469 } 2470 if (!DemandedElts[i]) 2471 continue; 2472 if (Scl && Scl != Op) 2473 return false; 2474 Scl = Op; 2475 } 2476 return true; 2477 } 2478 case ISD::VECTOR_SHUFFLE: { 2479 // Check if this is a shuffle node doing a splat. 2480 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2481 int SplatIndex = -1; 2482 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2483 for (int i = 0; i != (int)NumElts; ++i) { 2484 int M = Mask[i]; 2485 if (M < 0) { 2486 UndefElts.setBit(i); 2487 continue; 2488 } 2489 if (!DemandedElts[i]) 2490 continue; 2491 if (0 <= SplatIndex && SplatIndex != M) 2492 return false; 2493 SplatIndex = M; 2494 } 2495 return true; 2496 } 2497 case ISD::EXTRACT_SUBVECTOR: { 2498 // Offset the demanded elts by the subvector index. 2499 SDValue Src = V.getOperand(0); 2500 uint64_t Idx = V.getConstantOperandVal(1); 2501 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2502 APInt UndefSrcElts; 2503 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2504 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2505 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2506 return true; 2507 } 2508 break; 2509 } 2510 } 2511 2512 return false; 2513 } 2514 2515 /// Helper wrapper to main isSplatValue function. 2516 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2517 EVT VT = V.getValueType(); 2518 assert(VT.isVector() && "Vector type expected"); 2519 2520 APInt UndefElts; 2521 APInt DemandedElts; 2522 2523 // For now we don't support this with scalable vectors. 2524 if (!VT.isScalableVector()) 2525 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2526 return isSplatValue(V, DemandedElts, UndefElts) && 2527 (AllowUndefs || !UndefElts); 2528 } 2529 2530 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2531 V = peekThroughExtractSubvectors(V); 2532 2533 EVT VT = V.getValueType(); 2534 unsigned Opcode = V.getOpcode(); 2535 switch (Opcode) { 2536 default: { 2537 APInt UndefElts; 2538 APInt DemandedElts; 2539 2540 if (!VT.isScalableVector()) 2541 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2542 2543 if (isSplatValue(V, DemandedElts, UndefElts)) { 2544 if (VT.isScalableVector()) { 2545 // DemandedElts and UndefElts are ignored for scalable vectors, since 2546 // the only supported cases are SPLAT_VECTOR nodes. 2547 SplatIdx = 0; 2548 } else { 2549 // Handle case where all demanded elements are UNDEF. 2550 if (DemandedElts.isSubsetOf(UndefElts)) { 2551 SplatIdx = 0; 2552 return getUNDEF(VT); 2553 } 2554 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2555 } 2556 return V; 2557 } 2558 break; 2559 } 2560 case ISD::SPLAT_VECTOR: 2561 SplatIdx = 0; 2562 return V; 2563 case ISD::VECTOR_SHUFFLE: { 2564 if (VT.isScalableVector()) 2565 return SDValue(); 2566 2567 // Check if this is a shuffle node doing a splat. 2568 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2569 // getTargetVShiftNode currently struggles without the splat source. 2570 auto *SVN = cast<ShuffleVectorSDNode>(V); 2571 if (!SVN->isSplat()) 2572 break; 2573 int Idx = SVN->getSplatIndex(); 2574 int NumElts = V.getValueType().getVectorNumElements(); 2575 SplatIdx = Idx % NumElts; 2576 return V.getOperand(Idx / NumElts); 2577 } 2578 } 2579 2580 return SDValue(); 2581 } 2582 2583 SDValue SelectionDAG::getSplatValue(SDValue V) { 2584 int SplatIdx; 2585 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) 2586 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), 2587 SrcVector.getValueType().getScalarType(), SrcVector, 2588 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2589 return SDValue(); 2590 } 2591 2592 const APInt * 2593 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2594 const APInt &DemandedElts) const { 2595 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2596 V.getOpcode() == ISD::SRA) && 2597 "Unknown shift node"); 2598 unsigned BitWidth = V.getScalarValueSizeInBits(); 2599 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2600 // Shifting more than the bitwidth is not valid. 2601 const APInt &ShAmt = SA->getAPIntValue(); 2602 if (ShAmt.ult(BitWidth)) 2603 return &ShAmt; 2604 } 2605 return nullptr; 2606 } 2607 2608 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2609 SDValue V, const APInt &DemandedElts) const { 2610 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2611 V.getOpcode() == ISD::SRA) && 2612 "Unknown shift node"); 2613 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2614 return ValidAmt; 2615 unsigned BitWidth = V.getScalarValueSizeInBits(); 2616 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2617 if (!BV) 2618 return nullptr; 2619 const APInt *MinShAmt = nullptr; 2620 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2621 if (!DemandedElts[i]) 2622 continue; 2623 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2624 if (!SA) 2625 return nullptr; 2626 // Shifting more than the bitwidth is not valid. 2627 const APInt &ShAmt = SA->getAPIntValue(); 2628 if (ShAmt.uge(BitWidth)) 2629 return nullptr; 2630 if (MinShAmt && MinShAmt->ule(ShAmt)) 2631 continue; 2632 MinShAmt = &ShAmt; 2633 } 2634 return MinShAmt; 2635 } 2636 2637 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2638 SDValue V, const APInt &DemandedElts) const { 2639 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2640 V.getOpcode() == ISD::SRA) && 2641 "Unknown shift node"); 2642 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2643 return ValidAmt; 2644 unsigned BitWidth = V.getScalarValueSizeInBits(); 2645 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2646 if (!BV) 2647 return nullptr; 2648 const APInt *MaxShAmt = nullptr; 2649 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2650 if (!DemandedElts[i]) 2651 continue; 2652 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2653 if (!SA) 2654 return nullptr; 2655 // Shifting more than the bitwidth is not valid. 2656 const APInt &ShAmt = SA->getAPIntValue(); 2657 if (ShAmt.uge(BitWidth)) 2658 return nullptr; 2659 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2660 continue; 2661 MaxShAmt = &ShAmt; 2662 } 2663 return MaxShAmt; 2664 } 2665 2666 /// Determine which bits of Op are known to be either zero or one and return 2667 /// them in Known. For vectors, the known bits are those that are shared by 2668 /// every vector element. 2669 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2670 EVT VT = Op.getValueType(); 2671 2672 // TOOD: Until we have a plan for how to represent demanded elements for 2673 // scalable vectors, we can just bail out for now. 2674 if (Op.getValueType().isScalableVector()) { 2675 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2676 return KnownBits(BitWidth); 2677 } 2678 2679 APInt DemandedElts = VT.isVector() 2680 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2681 : APInt(1, 1); 2682 return computeKnownBits(Op, DemandedElts, Depth); 2683 } 2684 2685 /// Determine which bits of Op are known to be either zero or one and return 2686 /// them in Known. The DemandedElts argument allows us to only collect the known 2687 /// bits that are shared by the requested vector elements. 2688 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2689 unsigned Depth) const { 2690 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2691 2692 KnownBits Known(BitWidth); // Don't know anything. 2693 2694 // TOOD: Until we have a plan for how to represent demanded elements for 2695 // scalable vectors, we can just bail out for now. 2696 if (Op.getValueType().isScalableVector()) 2697 return Known; 2698 2699 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2700 // We know all of the bits for a constant! 2701 return KnownBits::makeConstant(C->getAPIntValue()); 2702 } 2703 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2704 // We know all of the bits for a constant fp! 2705 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2706 } 2707 2708 if (Depth >= MaxRecursionDepth) 2709 return Known; // Limit search depth. 2710 2711 KnownBits Known2; 2712 unsigned NumElts = DemandedElts.getBitWidth(); 2713 assert((!Op.getValueType().isVector() || 2714 NumElts == Op.getValueType().getVectorNumElements()) && 2715 "Unexpected vector size"); 2716 2717 if (!DemandedElts) 2718 return Known; // No demanded elts, better to assume we don't know anything. 2719 2720 unsigned Opcode = Op.getOpcode(); 2721 switch (Opcode) { 2722 case ISD::BUILD_VECTOR: 2723 // Collect the known bits that are shared by every demanded vector element. 2724 Known.Zero.setAllBits(); Known.One.setAllBits(); 2725 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2726 if (!DemandedElts[i]) 2727 continue; 2728 2729 SDValue SrcOp = Op.getOperand(i); 2730 Known2 = computeKnownBits(SrcOp, Depth + 1); 2731 2732 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2733 if (SrcOp.getValueSizeInBits() != BitWidth) { 2734 assert(SrcOp.getValueSizeInBits() > BitWidth && 2735 "Expected BUILD_VECTOR implicit truncation"); 2736 Known2 = Known2.trunc(BitWidth); 2737 } 2738 2739 // Known bits are the values that are shared by every demanded element. 2740 Known = KnownBits::commonBits(Known, Known2); 2741 2742 // If we don't know any bits, early out. 2743 if (Known.isUnknown()) 2744 break; 2745 } 2746 break; 2747 case ISD::VECTOR_SHUFFLE: { 2748 // Collect the known bits that are shared by every vector element referenced 2749 // by the shuffle. 2750 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2751 Known.Zero.setAllBits(); Known.One.setAllBits(); 2752 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2753 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2754 for (unsigned i = 0; i != NumElts; ++i) { 2755 if (!DemandedElts[i]) 2756 continue; 2757 2758 int M = SVN->getMaskElt(i); 2759 if (M < 0) { 2760 // For UNDEF elements, we don't know anything about the common state of 2761 // the shuffle result. 2762 Known.resetAll(); 2763 DemandedLHS.clearAllBits(); 2764 DemandedRHS.clearAllBits(); 2765 break; 2766 } 2767 2768 if ((unsigned)M < NumElts) 2769 DemandedLHS.setBit((unsigned)M % NumElts); 2770 else 2771 DemandedRHS.setBit((unsigned)M % NumElts); 2772 } 2773 // Known bits are the values that are shared by every demanded element. 2774 if (!!DemandedLHS) { 2775 SDValue LHS = Op.getOperand(0); 2776 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2777 Known = KnownBits::commonBits(Known, Known2); 2778 } 2779 // If we don't know any bits, early out. 2780 if (Known.isUnknown()) 2781 break; 2782 if (!!DemandedRHS) { 2783 SDValue RHS = Op.getOperand(1); 2784 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2785 Known = KnownBits::commonBits(Known, Known2); 2786 } 2787 break; 2788 } 2789 case ISD::CONCAT_VECTORS: { 2790 // Split DemandedElts and test each of the demanded subvectors. 2791 Known.Zero.setAllBits(); Known.One.setAllBits(); 2792 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2793 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2794 unsigned NumSubVectors = Op.getNumOperands(); 2795 for (unsigned i = 0; i != NumSubVectors; ++i) { 2796 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 2797 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 2798 if (!!DemandedSub) { 2799 SDValue Sub = Op.getOperand(i); 2800 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2801 Known = KnownBits::commonBits(Known, Known2); 2802 } 2803 // If we don't know any bits, early out. 2804 if (Known.isUnknown()) 2805 break; 2806 } 2807 break; 2808 } 2809 case ISD::INSERT_SUBVECTOR: { 2810 // Demand any elements from the subvector and the remainder from the src its 2811 // inserted into. 2812 SDValue Src = Op.getOperand(0); 2813 SDValue Sub = Op.getOperand(1); 2814 uint64_t Idx = Op.getConstantOperandVal(2); 2815 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2816 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2817 APInt DemandedSrcElts = DemandedElts; 2818 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2819 2820 Known.One.setAllBits(); 2821 Known.Zero.setAllBits(); 2822 if (!!DemandedSubElts) { 2823 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2824 if (Known.isUnknown()) 2825 break; // early-out. 2826 } 2827 if (!!DemandedSrcElts) { 2828 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2829 Known = KnownBits::commonBits(Known, Known2); 2830 } 2831 break; 2832 } 2833 case ISD::EXTRACT_SUBVECTOR: { 2834 // Offset the demanded elts by the subvector index. 2835 SDValue Src = Op.getOperand(0); 2836 // Bail until we can represent demanded elements for scalable vectors. 2837 if (Src.getValueType().isScalableVector()) 2838 break; 2839 uint64_t Idx = Op.getConstantOperandVal(1); 2840 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2841 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2842 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2843 break; 2844 } 2845 case ISD::SCALAR_TO_VECTOR: { 2846 // We know about scalar_to_vector as much as we know about it source, 2847 // which becomes the first element of otherwise unknown vector. 2848 if (DemandedElts != 1) 2849 break; 2850 2851 SDValue N0 = Op.getOperand(0); 2852 Known = computeKnownBits(N0, Depth + 1); 2853 if (N0.getValueSizeInBits() != BitWidth) 2854 Known = Known.trunc(BitWidth); 2855 2856 break; 2857 } 2858 case ISD::BITCAST: { 2859 SDValue N0 = Op.getOperand(0); 2860 EVT SubVT = N0.getValueType(); 2861 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2862 2863 // Ignore bitcasts from unsupported types. 2864 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2865 break; 2866 2867 // Fast handling of 'identity' bitcasts. 2868 if (BitWidth == SubBitWidth) { 2869 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2870 break; 2871 } 2872 2873 bool IsLE = getDataLayout().isLittleEndian(); 2874 2875 // Bitcast 'small element' vector to 'large element' scalar/vector. 2876 if ((BitWidth % SubBitWidth) == 0) { 2877 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2878 2879 // Collect known bits for the (larger) output by collecting the known 2880 // bits from each set of sub elements and shift these into place. 2881 // We need to separately call computeKnownBits for each set of 2882 // sub elements as the knownbits for each is likely to be different. 2883 unsigned SubScale = BitWidth / SubBitWidth; 2884 APInt SubDemandedElts(NumElts * SubScale, 0); 2885 for (unsigned i = 0; i != NumElts; ++i) 2886 if (DemandedElts[i]) 2887 SubDemandedElts.setBit(i * SubScale); 2888 2889 for (unsigned i = 0; i != SubScale; ++i) { 2890 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2891 Depth + 1); 2892 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2893 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts); 2894 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts); 2895 } 2896 } 2897 2898 // Bitcast 'large element' scalar/vector to 'small element' vector. 2899 if ((SubBitWidth % BitWidth) == 0) { 2900 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2901 2902 // Collect known bits for the (smaller) output by collecting the known 2903 // bits from the overlapping larger input elements and extracting the 2904 // sub sections we actually care about. 2905 unsigned SubScale = SubBitWidth / BitWidth; 2906 APInt SubDemandedElts(NumElts / SubScale, 0); 2907 for (unsigned i = 0; i != NumElts; ++i) 2908 if (DemandedElts[i]) 2909 SubDemandedElts.setBit(i / SubScale); 2910 2911 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2912 2913 Known.Zero.setAllBits(); Known.One.setAllBits(); 2914 for (unsigned i = 0; i != NumElts; ++i) 2915 if (DemandedElts[i]) { 2916 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2917 unsigned Offset = (Shifts % SubScale) * BitWidth; 2918 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth); 2919 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth); 2920 // If we don't know any bits, early out. 2921 if (Known.isUnknown()) 2922 break; 2923 } 2924 } 2925 break; 2926 } 2927 case ISD::AND: 2928 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2929 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2930 2931 Known &= Known2; 2932 break; 2933 case ISD::OR: 2934 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2935 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2936 2937 Known |= Known2; 2938 break; 2939 case ISD::XOR: 2940 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2941 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2942 2943 Known ^= Known2; 2944 break; 2945 case ISD::MUL: { 2946 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2947 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2948 Known = KnownBits::computeForMul(Known, Known2); 2949 break; 2950 } 2951 case ISD::UDIV: { 2952 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2953 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2954 Known = KnownBits::udiv(Known, Known2); 2955 break; 2956 } 2957 case ISD::SELECT: 2958 case ISD::VSELECT: 2959 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2960 // If we don't know any bits, early out. 2961 if (Known.isUnknown()) 2962 break; 2963 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 2964 2965 // Only known if known in both the LHS and RHS. 2966 Known = KnownBits::commonBits(Known, Known2); 2967 break; 2968 case ISD::SELECT_CC: 2969 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 2970 // If we don't know any bits, early out. 2971 if (Known.isUnknown()) 2972 break; 2973 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 2974 2975 // Only known if known in both the LHS and RHS. 2976 Known = KnownBits::commonBits(Known, Known2); 2977 break; 2978 case ISD::SMULO: 2979 case ISD::UMULO: 2980 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 2981 if (Op.getResNo() != 1) 2982 break; 2983 // The boolean result conforms to getBooleanContents. 2984 // If we know the result of a setcc has the top bits zero, use this info. 2985 // We know that we have an integer-based boolean since these operations 2986 // are only available for integer. 2987 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2988 TargetLowering::ZeroOrOneBooleanContent && 2989 BitWidth > 1) 2990 Known.Zero.setBitsFrom(1); 2991 break; 2992 case ISD::SETCC: 2993 case ISD::STRICT_FSETCC: 2994 case ISD::STRICT_FSETCCS: { 2995 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 2996 // If we know the result of a setcc has the top bits zero, use this info. 2997 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 2998 TargetLowering::ZeroOrOneBooleanContent && 2999 BitWidth > 1) 3000 Known.Zero.setBitsFrom(1); 3001 break; 3002 } 3003 case ISD::SHL: 3004 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3005 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3006 Known = KnownBits::shl(Known, Known2); 3007 3008 // Minimum shift low bits are known zero. 3009 if (const APInt *ShMinAmt = 3010 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3011 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3012 break; 3013 case ISD::SRL: 3014 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3015 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3016 Known = KnownBits::lshr(Known, Known2); 3017 3018 // Minimum shift high bits are known zero. 3019 if (const APInt *ShMinAmt = 3020 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3021 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3022 break; 3023 case ISD::SRA: 3024 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3025 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3026 Known = KnownBits::ashr(Known, Known2); 3027 // TODO: Add minimum shift high known sign bits. 3028 break; 3029 case ISD::FSHL: 3030 case ISD::FSHR: 3031 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3032 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3033 3034 // For fshl, 0-shift returns the 1st arg. 3035 // For fshr, 0-shift returns the 2nd arg. 3036 if (Amt == 0) { 3037 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3038 DemandedElts, Depth + 1); 3039 break; 3040 } 3041 3042 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3043 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3044 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3045 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3046 if (Opcode == ISD::FSHL) { 3047 Known.One <<= Amt; 3048 Known.Zero <<= Amt; 3049 Known2.One.lshrInPlace(BitWidth - Amt); 3050 Known2.Zero.lshrInPlace(BitWidth - Amt); 3051 } else { 3052 Known.One <<= BitWidth - Amt; 3053 Known.Zero <<= BitWidth - Amt; 3054 Known2.One.lshrInPlace(Amt); 3055 Known2.Zero.lshrInPlace(Amt); 3056 } 3057 Known.One |= Known2.One; 3058 Known.Zero |= Known2.Zero; 3059 } 3060 break; 3061 case ISD::SIGN_EXTEND_INREG: { 3062 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3063 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3064 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3065 break; 3066 } 3067 case ISD::CTTZ: 3068 case ISD::CTTZ_ZERO_UNDEF: { 3069 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3070 // If we have a known 1, its position is our upper bound. 3071 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3072 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3073 Known.Zero.setBitsFrom(LowBits); 3074 break; 3075 } 3076 case ISD::CTLZ: 3077 case ISD::CTLZ_ZERO_UNDEF: { 3078 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3079 // If we have a known 1, its position is our upper bound. 3080 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3081 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3082 Known.Zero.setBitsFrom(LowBits); 3083 break; 3084 } 3085 case ISD::CTPOP: { 3086 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3087 // If we know some of the bits are zero, they can't be one. 3088 unsigned PossibleOnes = Known2.countMaxPopulation(); 3089 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3090 break; 3091 } 3092 case ISD::PARITY: { 3093 // Parity returns 0 everywhere but the LSB. 3094 Known.Zero.setBitsFrom(1); 3095 break; 3096 } 3097 case ISD::LOAD: { 3098 LoadSDNode *LD = cast<LoadSDNode>(Op); 3099 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3100 if (ISD::isNON_EXTLoad(LD) && Cst) { 3101 // Determine any common known bits from the loaded constant pool value. 3102 Type *CstTy = Cst->getType(); 3103 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3104 // If its a vector splat, then we can (quickly) reuse the scalar path. 3105 // NOTE: We assume all elements match and none are UNDEF. 3106 if (CstTy->isVectorTy()) { 3107 if (const Constant *Splat = Cst->getSplatValue()) { 3108 Cst = Splat; 3109 CstTy = Cst->getType(); 3110 } 3111 } 3112 // TODO - do we need to handle different bitwidths? 3113 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3114 // Iterate across all vector elements finding common known bits. 3115 Known.One.setAllBits(); 3116 Known.Zero.setAllBits(); 3117 for (unsigned i = 0; i != NumElts; ++i) { 3118 if (!DemandedElts[i]) 3119 continue; 3120 if (Constant *Elt = Cst->getAggregateElement(i)) { 3121 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3122 const APInt &Value = CInt->getValue(); 3123 Known.One &= Value; 3124 Known.Zero &= ~Value; 3125 continue; 3126 } 3127 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3128 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3129 Known.One &= Value; 3130 Known.Zero &= ~Value; 3131 continue; 3132 } 3133 } 3134 Known.One.clearAllBits(); 3135 Known.Zero.clearAllBits(); 3136 break; 3137 } 3138 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3139 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3140 Known = KnownBits::makeConstant(CInt->getValue()); 3141 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3142 Known = 3143 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3144 } 3145 } 3146 } 3147 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3148 // If this is a ZEXTLoad and we are looking at the loaded value. 3149 EVT VT = LD->getMemoryVT(); 3150 unsigned MemBits = VT.getScalarSizeInBits(); 3151 Known.Zero.setBitsFrom(MemBits); 3152 } else if (const MDNode *Ranges = LD->getRanges()) { 3153 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3154 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3155 } 3156 break; 3157 } 3158 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3159 EVT InVT = Op.getOperand(0).getValueType(); 3160 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3161 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3162 Known = Known.zext(BitWidth); 3163 break; 3164 } 3165 case ISD::ZERO_EXTEND: { 3166 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3167 Known = Known.zext(BitWidth); 3168 break; 3169 } 3170 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3171 EVT InVT = Op.getOperand(0).getValueType(); 3172 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3173 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3174 // If the sign bit is known to be zero or one, then sext will extend 3175 // it to the top bits, else it will just zext. 3176 Known = Known.sext(BitWidth); 3177 break; 3178 } 3179 case ISD::SIGN_EXTEND: { 3180 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3181 // If the sign bit is known to be zero or one, then sext will extend 3182 // it to the top bits, else it will just zext. 3183 Known = Known.sext(BitWidth); 3184 break; 3185 } 3186 case ISD::ANY_EXTEND_VECTOR_INREG: { 3187 EVT InVT = Op.getOperand(0).getValueType(); 3188 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3189 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3190 Known = Known.anyext(BitWidth); 3191 break; 3192 } 3193 case ISD::ANY_EXTEND: { 3194 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3195 Known = Known.anyext(BitWidth); 3196 break; 3197 } 3198 case ISD::TRUNCATE: { 3199 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3200 Known = Known.trunc(BitWidth); 3201 break; 3202 } 3203 case ISD::AssertZext: { 3204 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3205 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3206 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3207 Known.Zero |= (~InMask); 3208 Known.One &= (~Known.Zero); 3209 break; 3210 } 3211 case ISD::AssertAlign: { 3212 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3213 assert(LogOfAlign != 0); 3214 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3215 // well as clearing one bits. 3216 Known.Zero.setLowBits(LogOfAlign); 3217 Known.One.clearLowBits(LogOfAlign); 3218 break; 3219 } 3220 case ISD::FGETSIGN: 3221 // All bits are zero except the low bit. 3222 Known.Zero.setBitsFrom(1); 3223 break; 3224 case ISD::USUBO: 3225 case ISD::SSUBO: 3226 if (Op.getResNo() == 1) { 3227 // If we know the result of a setcc has the top bits zero, use this info. 3228 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3229 TargetLowering::ZeroOrOneBooleanContent && 3230 BitWidth > 1) 3231 Known.Zero.setBitsFrom(1); 3232 break; 3233 } 3234 LLVM_FALLTHROUGH; 3235 case ISD::SUB: 3236 case ISD::SUBC: { 3237 assert(Op.getResNo() == 0 && 3238 "We only compute knownbits for the difference here."); 3239 3240 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3241 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3242 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3243 Known, Known2); 3244 break; 3245 } 3246 case ISD::UADDO: 3247 case ISD::SADDO: 3248 case ISD::ADDCARRY: 3249 if (Op.getResNo() == 1) { 3250 // If we know the result of a setcc has the top bits zero, use this info. 3251 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3252 TargetLowering::ZeroOrOneBooleanContent && 3253 BitWidth > 1) 3254 Known.Zero.setBitsFrom(1); 3255 break; 3256 } 3257 LLVM_FALLTHROUGH; 3258 case ISD::ADD: 3259 case ISD::ADDC: 3260 case ISD::ADDE: { 3261 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3262 3263 // With ADDE and ADDCARRY, a carry bit may be added in. 3264 KnownBits Carry(1); 3265 if (Opcode == ISD::ADDE) 3266 // Can't track carry from glue, set carry to unknown. 3267 Carry.resetAll(); 3268 else if (Opcode == ISD::ADDCARRY) 3269 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3270 // the trouble (how often will we find a known carry bit). And I haven't 3271 // tested this very much yet, but something like this might work: 3272 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3273 // Carry = Carry.zextOrTrunc(1, false); 3274 Carry.resetAll(); 3275 else 3276 Carry.setAllZero(); 3277 3278 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3279 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3280 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3281 break; 3282 } 3283 case ISD::SREM: { 3284 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3285 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3286 Known = KnownBits::srem(Known, Known2); 3287 break; 3288 } 3289 case ISD::UREM: { 3290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3292 Known = KnownBits::urem(Known, Known2); 3293 break; 3294 } 3295 case ISD::EXTRACT_ELEMENT: { 3296 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3297 const unsigned Index = Op.getConstantOperandVal(1); 3298 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3299 3300 // Remove low part of known bits mask 3301 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3302 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3303 3304 // Remove high part of known bit mask 3305 Known = Known.trunc(EltBitWidth); 3306 break; 3307 } 3308 case ISD::EXTRACT_VECTOR_ELT: { 3309 SDValue InVec = Op.getOperand(0); 3310 SDValue EltNo = Op.getOperand(1); 3311 EVT VecVT = InVec.getValueType(); 3312 // computeKnownBits not yet implemented for scalable vectors. 3313 if (VecVT.isScalableVector()) 3314 break; 3315 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3316 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3317 3318 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3319 // anything about the extended bits. 3320 if (BitWidth > EltBitWidth) 3321 Known = Known.trunc(EltBitWidth); 3322 3323 // If we know the element index, just demand that vector element, else for 3324 // an unknown element index, ignore DemandedElts and demand them all. 3325 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3326 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3327 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3328 DemandedSrcElts = 3329 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3330 3331 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3332 if (BitWidth > EltBitWidth) 3333 Known = Known.anyext(BitWidth); 3334 break; 3335 } 3336 case ISD::INSERT_VECTOR_ELT: { 3337 // If we know the element index, split the demand between the 3338 // source vector and the inserted element, otherwise assume we need 3339 // the original demanded vector elements and the value. 3340 SDValue InVec = Op.getOperand(0); 3341 SDValue InVal = Op.getOperand(1); 3342 SDValue EltNo = Op.getOperand(2); 3343 bool DemandedVal = true; 3344 APInt DemandedVecElts = DemandedElts; 3345 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3346 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3347 unsigned EltIdx = CEltNo->getZExtValue(); 3348 DemandedVal = !!DemandedElts[EltIdx]; 3349 DemandedVecElts.clearBit(EltIdx); 3350 } 3351 Known.One.setAllBits(); 3352 Known.Zero.setAllBits(); 3353 if (DemandedVal) { 3354 Known2 = computeKnownBits(InVal, Depth + 1); 3355 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3356 } 3357 if (!!DemandedVecElts) { 3358 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3359 Known = KnownBits::commonBits(Known, Known2); 3360 } 3361 break; 3362 } 3363 case ISD::BITREVERSE: { 3364 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3365 Known = Known2.reverseBits(); 3366 break; 3367 } 3368 case ISD::BSWAP: { 3369 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3370 Known = Known2.byteSwap(); 3371 break; 3372 } 3373 case ISD::ABS: { 3374 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3375 Known = Known2.abs(); 3376 break; 3377 } 3378 case ISD::UMIN: { 3379 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3380 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3381 Known = KnownBits::umin(Known, Known2); 3382 break; 3383 } 3384 case ISD::UMAX: { 3385 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3386 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3387 Known = KnownBits::umax(Known, Known2); 3388 break; 3389 } 3390 case ISD::SMIN: 3391 case ISD::SMAX: { 3392 // If we have a clamp pattern, we know that the number of sign bits will be 3393 // the minimum of the clamp min/max range. 3394 bool IsMax = (Opcode == ISD::SMAX); 3395 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3396 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3397 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3398 CstHigh = 3399 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3400 if (CstLow && CstHigh) { 3401 if (!IsMax) 3402 std::swap(CstLow, CstHigh); 3403 3404 const APInt &ValueLow = CstLow->getAPIntValue(); 3405 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3406 if (ValueLow.sle(ValueHigh)) { 3407 unsigned LowSignBits = ValueLow.getNumSignBits(); 3408 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3409 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3410 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3411 Known.One.setHighBits(MinSignBits); 3412 break; 3413 } 3414 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3415 Known.Zero.setHighBits(MinSignBits); 3416 break; 3417 } 3418 } 3419 } 3420 3421 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3422 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3423 if (IsMax) 3424 Known = KnownBits::smax(Known, Known2); 3425 else 3426 Known = KnownBits::smin(Known, Known2); 3427 break; 3428 } 3429 case ISD::FrameIndex: 3430 case ISD::TargetFrameIndex: 3431 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3432 Known, getMachineFunction()); 3433 break; 3434 3435 default: 3436 if (Opcode < ISD::BUILTIN_OP_END) 3437 break; 3438 LLVM_FALLTHROUGH; 3439 case ISD::INTRINSIC_WO_CHAIN: 3440 case ISD::INTRINSIC_W_CHAIN: 3441 case ISD::INTRINSIC_VOID: 3442 // Allow the target to implement this method for its nodes. 3443 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3444 break; 3445 } 3446 3447 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3448 return Known; 3449 } 3450 3451 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3452 SDValue N1) const { 3453 // X + 0 never overflow 3454 if (isNullConstant(N1)) 3455 return OFK_Never; 3456 3457 KnownBits N1Known = computeKnownBits(N1); 3458 if (N1Known.Zero.getBoolValue()) { 3459 KnownBits N0Known = computeKnownBits(N0); 3460 3461 bool overflow; 3462 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3463 if (!overflow) 3464 return OFK_Never; 3465 } 3466 3467 // mulhi + 1 never overflow 3468 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3469 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3470 return OFK_Never; 3471 3472 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3473 KnownBits N0Known = computeKnownBits(N0); 3474 3475 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3476 return OFK_Never; 3477 } 3478 3479 return OFK_Sometime; 3480 } 3481 3482 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3483 EVT OpVT = Val.getValueType(); 3484 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3485 3486 // Is the constant a known power of 2? 3487 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3488 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3489 3490 // A left-shift of a constant one will have exactly one bit set because 3491 // shifting the bit off the end is undefined. 3492 if (Val.getOpcode() == ISD::SHL) { 3493 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3494 if (C && C->getAPIntValue() == 1) 3495 return true; 3496 } 3497 3498 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3499 // one bit set. 3500 if (Val.getOpcode() == ISD::SRL) { 3501 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3502 if (C && C->getAPIntValue().isSignMask()) 3503 return true; 3504 } 3505 3506 // Are all operands of a build vector constant powers of two? 3507 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3508 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3510 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3511 return false; 3512 })) 3513 return true; 3514 3515 // More could be done here, though the above checks are enough 3516 // to handle some common cases. 3517 3518 // Fall back to computeKnownBits to catch other known cases. 3519 KnownBits Known = computeKnownBits(Val); 3520 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3521 } 3522 3523 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3524 EVT VT = Op.getValueType(); 3525 3526 // TODO: Assume we don't know anything for now. 3527 if (VT.isScalableVector()) 3528 return 1; 3529 3530 APInt DemandedElts = VT.isVector() 3531 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3532 : APInt(1, 1); 3533 return ComputeNumSignBits(Op, DemandedElts, Depth); 3534 } 3535 3536 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3537 unsigned Depth) const { 3538 EVT VT = Op.getValueType(); 3539 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3540 unsigned VTBits = VT.getScalarSizeInBits(); 3541 unsigned NumElts = DemandedElts.getBitWidth(); 3542 unsigned Tmp, Tmp2; 3543 unsigned FirstAnswer = 1; 3544 3545 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3546 const APInt &Val = C->getAPIntValue(); 3547 return Val.getNumSignBits(); 3548 } 3549 3550 if (Depth >= MaxRecursionDepth) 3551 return 1; // Limit search depth. 3552 3553 if (!DemandedElts || VT.isScalableVector()) 3554 return 1; // No demanded elts, better to assume we don't know anything. 3555 3556 unsigned Opcode = Op.getOpcode(); 3557 switch (Opcode) { 3558 default: break; 3559 case ISD::AssertSext: 3560 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3561 return VTBits-Tmp+1; 3562 case ISD::AssertZext: 3563 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3564 return VTBits-Tmp; 3565 3566 case ISD::BUILD_VECTOR: 3567 Tmp = VTBits; 3568 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3569 if (!DemandedElts[i]) 3570 continue; 3571 3572 SDValue SrcOp = Op.getOperand(i); 3573 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3574 3575 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3576 if (SrcOp.getValueSizeInBits() != VTBits) { 3577 assert(SrcOp.getValueSizeInBits() > VTBits && 3578 "Expected BUILD_VECTOR implicit truncation"); 3579 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3580 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3581 } 3582 Tmp = std::min(Tmp, Tmp2); 3583 } 3584 return Tmp; 3585 3586 case ISD::VECTOR_SHUFFLE: { 3587 // Collect the minimum number of sign bits that are shared by every vector 3588 // element referenced by the shuffle. 3589 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3590 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3591 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3592 for (unsigned i = 0; i != NumElts; ++i) { 3593 int M = SVN->getMaskElt(i); 3594 if (!DemandedElts[i]) 3595 continue; 3596 // For UNDEF elements, we don't know anything about the common state of 3597 // the shuffle result. 3598 if (M < 0) 3599 return 1; 3600 if ((unsigned)M < NumElts) 3601 DemandedLHS.setBit((unsigned)M % NumElts); 3602 else 3603 DemandedRHS.setBit((unsigned)M % NumElts); 3604 } 3605 Tmp = std::numeric_limits<unsigned>::max(); 3606 if (!!DemandedLHS) 3607 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3608 if (!!DemandedRHS) { 3609 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3610 Tmp = std::min(Tmp, Tmp2); 3611 } 3612 // If we don't know anything, early out and try computeKnownBits fall-back. 3613 if (Tmp == 1) 3614 break; 3615 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3616 return Tmp; 3617 } 3618 3619 case ISD::BITCAST: { 3620 SDValue N0 = Op.getOperand(0); 3621 EVT SrcVT = N0.getValueType(); 3622 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3623 3624 // Ignore bitcasts from unsupported types.. 3625 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3626 break; 3627 3628 // Fast handling of 'identity' bitcasts. 3629 if (VTBits == SrcBits) 3630 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3631 3632 bool IsLE = getDataLayout().isLittleEndian(); 3633 3634 // Bitcast 'large element' scalar/vector to 'small element' vector. 3635 if ((SrcBits % VTBits) == 0) { 3636 assert(VT.isVector() && "Expected bitcast to vector"); 3637 3638 unsigned Scale = SrcBits / VTBits; 3639 APInt SrcDemandedElts(NumElts / Scale, 0); 3640 for (unsigned i = 0; i != NumElts; ++i) 3641 if (DemandedElts[i]) 3642 SrcDemandedElts.setBit(i / Scale); 3643 3644 // Fast case - sign splat can be simply split across the small elements. 3645 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3646 if (Tmp == SrcBits) 3647 return VTBits; 3648 3649 // Slow case - determine how far the sign extends into each sub-element. 3650 Tmp2 = VTBits; 3651 for (unsigned i = 0; i != NumElts; ++i) 3652 if (DemandedElts[i]) { 3653 unsigned SubOffset = i % Scale; 3654 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3655 SubOffset = SubOffset * VTBits; 3656 if (Tmp <= SubOffset) 3657 return 1; 3658 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3659 } 3660 return Tmp2; 3661 } 3662 break; 3663 } 3664 3665 case ISD::SIGN_EXTEND: 3666 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3667 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3668 case ISD::SIGN_EXTEND_INREG: 3669 // Max of the input and what this extends. 3670 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3671 Tmp = VTBits-Tmp+1; 3672 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3673 return std::max(Tmp, Tmp2); 3674 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3675 SDValue Src = Op.getOperand(0); 3676 EVT SrcVT = Src.getValueType(); 3677 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3678 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3679 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3680 } 3681 case ISD::SRA: 3682 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3683 // SRA X, C -> adds C sign bits. 3684 if (const APInt *ShAmt = 3685 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3686 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3687 return Tmp; 3688 case ISD::SHL: 3689 if (const APInt *ShAmt = 3690 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3691 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3692 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3693 if (ShAmt->ult(Tmp)) 3694 return Tmp - ShAmt->getZExtValue(); 3695 } 3696 break; 3697 case ISD::AND: 3698 case ISD::OR: 3699 case ISD::XOR: // NOT is handled here. 3700 // Logical binary ops preserve the number of sign bits at the worst. 3701 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3702 if (Tmp != 1) { 3703 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3704 FirstAnswer = std::min(Tmp, Tmp2); 3705 // We computed what we know about the sign bits as our first 3706 // answer. Now proceed to the generic code that uses 3707 // computeKnownBits, and pick whichever answer is better. 3708 } 3709 break; 3710 3711 case ISD::SELECT: 3712 case ISD::VSELECT: 3713 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3714 if (Tmp == 1) return 1; // Early out. 3715 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3716 return std::min(Tmp, Tmp2); 3717 case ISD::SELECT_CC: 3718 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3719 if (Tmp == 1) return 1; // Early out. 3720 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3721 return std::min(Tmp, Tmp2); 3722 3723 case ISD::SMIN: 3724 case ISD::SMAX: { 3725 // If we have a clamp pattern, we know that the number of sign bits will be 3726 // the minimum of the clamp min/max range. 3727 bool IsMax = (Opcode == ISD::SMAX); 3728 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3729 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3730 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3731 CstHigh = 3732 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3733 if (CstLow && CstHigh) { 3734 if (!IsMax) 3735 std::swap(CstLow, CstHigh); 3736 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3737 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3738 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3739 return std::min(Tmp, Tmp2); 3740 } 3741 } 3742 3743 // Fallback - just get the minimum number of sign bits of the operands. 3744 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3745 if (Tmp == 1) 3746 return 1; // Early out. 3747 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3748 return std::min(Tmp, Tmp2); 3749 } 3750 case ISD::UMIN: 3751 case ISD::UMAX: 3752 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3753 if (Tmp == 1) 3754 return 1; // Early out. 3755 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3756 return std::min(Tmp, Tmp2); 3757 case ISD::SADDO: 3758 case ISD::UADDO: 3759 case ISD::SSUBO: 3760 case ISD::USUBO: 3761 case ISD::SMULO: 3762 case ISD::UMULO: 3763 if (Op.getResNo() != 1) 3764 break; 3765 // The boolean result conforms to getBooleanContents. Fall through. 3766 // If setcc returns 0/-1, all bits are sign bits. 3767 // We know that we have an integer-based boolean since these operations 3768 // are only available for integer. 3769 if (TLI->getBooleanContents(VT.isVector(), false) == 3770 TargetLowering::ZeroOrNegativeOneBooleanContent) 3771 return VTBits; 3772 break; 3773 case ISD::SETCC: 3774 case ISD::STRICT_FSETCC: 3775 case ISD::STRICT_FSETCCS: { 3776 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3777 // If setcc returns 0/-1, all bits are sign bits. 3778 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3779 TargetLowering::ZeroOrNegativeOneBooleanContent) 3780 return VTBits; 3781 break; 3782 } 3783 case ISD::ROTL: 3784 case ISD::ROTR: 3785 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3786 3787 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3788 if (Tmp == VTBits) 3789 return VTBits; 3790 3791 if (ConstantSDNode *C = 3792 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3793 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3794 3795 // Handle rotate right by N like a rotate left by 32-N. 3796 if (Opcode == ISD::ROTR) 3797 RotAmt = (VTBits - RotAmt) % VTBits; 3798 3799 // If we aren't rotating out all of the known-in sign bits, return the 3800 // number that are left. This handles rotl(sext(x), 1) for example. 3801 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3802 } 3803 break; 3804 case ISD::ADD: 3805 case ISD::ADDC: 3806 // Add can have at most one carry bit. Thus we know that the output 3807 // is, at worst, one more bit than the inputs. 3808 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3809 if (Tmp == 1) return 1; // Early out. 3810 3811 // Special case decrementing a value (ADD X, -1): 3812 if (ConstantSDNode *CRHS = 3813 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3814 if (CRHS->isAllOnesValue()) { 3815 KnownBits Known = 3816 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3817 3818 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3819 // sign bits set. 3820 if ((Known.Zero | 1).isAllOnesValue()) 3821 return VTBits; 3822 3823 // If we are subtracting one from a positive number, there is no carry 3824 // out of the result. 3825 if (Known.isNonNegative()) 3826 return Tmp; 3827 } 3828 3829 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3830 if (Tmp2 == 1) return 1; // Early out. 3831 return std::min(Tmp, Tmp2) - 1; 3832 case ISD::SUB: 3833 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3834 if (Tmp2 == 1) return 1; // Early out. 3835 3836 // Handle NEG. 3837 if (ConstantSDNode *CLHS = 3838 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3839 if (CLHS->isNullValue()) { 3840 KnownBits Known = 3841 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3842 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3843 // sign bits set. 3844 if ((Known.Zero | 1).isAllOnesValue()) 3845 return VTBits; 3846 3847 // If the input is known to be positive (the sign bit is known clear), 3848 // the output of the NEG has the same number of sign bits as the input. 3849 if (Known.isNonNegative()) 3850 return Tmp2; 3851 3852 // Otherwise, we treat this like a SUB. 3853 } 3854 3855 // Sub can have at most one carry bit. Thus we know that the output 3856 // is, at worst, one more bit than the inputs. 3857 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3858 if (Tmp == 1) return 1; // Early out. 3859 return std::min(Tmp, Tmp2) - 1; 3860 case ISD::MUL: { 3861 // The output of the Mul can be at most twice the valid bits in the inputs. 3862 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3863 if (SignBitsOp0 == 1) 3864 break; 3865 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 3866 if (SignBitsOp1 == 1) 3867 break; 3868 unsigned OutValidBits = 3869 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 3870 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 3871 } 3872 case ISD::SREM: 3873 // The sign bit is the LHS's sign bit, except when the result of the 3874 // remainder is zero. The magnitude of the result should be less than or 3875 // equal to the magnitude of the LHS. Therefore, the result should have 3876 // at least as many sign bits as the left hand side. 3877 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3878 case ISD::TRUNCATE: { 3879 // Check if the sign bits of source go down as far as the truncated value. 3880 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 3881 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3882 if (NumSrcSignBits > (NumSrcBits - VTBits)) 3883 return NumSrcSignBits - (NumSrcBits - VTBits); 3884 break; 3885 } 3886 case ISD::EXTRACT_ELEMENT: { 3887 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 3888 const int BitWidth = Op.getValueSizeInBits(); 3889 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 3890 3891 // Get reverse index (starting from 1), Op1 value indexes elements from 3892 // little end. Sign starts at big end. 3893 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 3894 3895 // If the sign portion ends in our element the subtraction gives correct 3896 // result. Otherwise it gives either negative or > bitwidth result 3897 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 3898 } 3899 case ISD::INSERT_VECTOR_ELT: { 3900 // If we know the element index, split the demand between the 3901 // source vector and the inserted element, otherwise assume we need 3902 // the original demanded vector elements and the value. 3903 SDValue InVec = Op.getOperand(0); 3904 SDValue InVal = Op.getOperand(1); 3905 SDValue EltNo = Op.getOperand(2); 3906 bool DemandedVal = true; 3907 APInt DemandedVecElts = DemandedElts; 3908 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3909 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3910 unsigned EltIdx = CEltNo->getZExtValue(); 3911 DemandedVal = !!DemandedElts[EltIdx]; 3912 DemandedVecElts.clearBit(EltIdx); 3913 } 3914 Tmp = std::numeric_limits<unsigned>::max(); 3915 if (DemandedVal) { 3916 // TODO - handle implicit truncation of inserted elements. 3917 if (InVal.getScalarValueSizeInBits() != VTBits) 3918 break; 3919 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 3920 Tmp = std::min(Tmp, Tmp2); 3921 } 3922 if (!!DemandedVecElts) { 3923 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 3924 Tmp = std::min(Tmp, Tmp2); 3925 } 3926 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3927 return Tmp; 3928 } 3929 case ISD::EXTRACT_VECTOR_ELT: { 3930 SDValue InVec = Op.getOperand(0); 3931 SDValue EltNo = Op.getOperand(1); 3932 EVT VecVT = InVec.getValueType(); 3933 // ComputeNumSignBits not yet implemented for scalable vectors. 3934 if (VecVT.isScalableVector()) 3935 break; 3936 const unsigned BitWidth = Op.getValueSizeInBits(); 3937 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 3938 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3939 3940 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 3941 // anything about sign bits. But if the sizes match we can derive knowledge 3942 // about sign bits from the vector operand. 3943 if (BitWidth != EltBitWidth) 3944 break; 3945 3946 // If we know the element index, just demand that vector element, else for 3947 // an unknown element index, ignore DemandedElts and demand them all. 3948 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3949 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3950 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3951 DemandedSrcElts = 3952 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3953 3954 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 3955 } 3956 case ISD::EXTRACT_SUBVECTOR: { 3957 // Offset the demanded elts by the subvector index. 3958 SDValue Src = Op.getOperand(0); 3959 // Bail until we can represent demanded elements for scalable vectors. 3960 if (Src.getValueType().isScalableVector()) 3961 break; 3962 uint64_t Idx = Op.getConstantOperandVal(1); 3963 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3964 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3965 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 3966 } 3967 case ISD::CONCAT_VECTORS: { 3968 // Determine the minimum number of sign bits across all demanded 3969 // elts of the input vectors. Early out if the result is already 1. 3970 Tmp = std::numeric_limits<unsigned>::max(); 3971 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3972 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3973 unsigned NumSubVectors = Op.getNumOperands(); 3974 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 3975 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 3976 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 3977 if (!DemandedSub) 3978 continue; 3979 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 3980 Tmp = std::min(Tmp, Tmp2); 3981 } 3982 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3983 return Tmp; 3984 } 3985 case ISD::INSERT_SUBVECTOR: { 3986 // Demand any elements from the subvector and the remainder from the src its 3987 // inserted into. 3988 SDValue Src = Op.getOperand(0); 3989 SDValue Sub = Op.getOperand(1); 3990 uint64_t Idx = Op.getConstantOperandVal(2); 3991 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3992 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3993 APInt DemandedSrcElts = DemandedElts; 3994 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 3995 3996 Tmp = std::numeric_limits<unsigned>::max(); 3997 if (!!DemandedSubElts) { 3998 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 3999 if (Tmp == 1) 4000 return 1; // early-out 4001 } 4002 if (!!DemandedSrcElts) { 4003 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4004 Tmp = std::min(Tmp, Tmp2); 4005 } 4006 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4007 return Tmp; 4008 } 4009 } 4010 4011 // If we are looking at the loaded value of the SDNode. 4012 if (Op.getResNo() == 0) { 4013 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4014 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4015 unsigned ExtType = LD->getExtensionType(); 4016 switch (ExtType) { 4017 default: break; 4018 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4019 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4020 return VTBits - Tmp + 1; 4021 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4022 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4023 return VTBits - Tmp; 4024 case ISD::NON_EXTLOAD: 4025 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4026 // We only need to handle vectors - computeKnownBits should handle 4027 // scalar cases. 4028 Type *CstTy = Cst->getType(); 4029 if (CstTy->isVectorTy() && 4030 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4031 Tmp = VTBits; 4032 for (unsigned i = 0; i != NumElts; ++i) { 4033 if (!DemandedElts[i]) 4034 continue; 4035 if (Constant *Elt = Cst->getAggregateElement(i)) { 4036 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4037 const APInt &Value = CInt->getValue(); 4038 Tmp = std::min(Tmp, Value.getNumSignBits()); 4039 continue; 4040 } 4041 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4042 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4043 Tmp = std::min(Tmp, Value.getNumSignBits()); 4044 continue; 4045 } 4046 } 4047 // Unknown type. Conservatively assume no bits match sign bit. 4048 return 1; 4049 } 4050 return Tmp; 4051 } 4052 } 4053 break; 4054 } 4055 } 4056 } 4057 4058 // Allow the target to implement this method for its nodes. 4059 if (Opcode >= ISD::BUILTIN_OP_END || 4060 Opcode == ISD::INTRINSIC_WO_CHAIN || 4061 Opcode == ISD::INTRINSIC_W_CHAIN || 4062 Opcode == ISD::INTRINSIC_VOID) { 4063 unsigned NumBits = 4064 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4065 if (NumBits > 1) 4066 FirstAnswer = std::max(FirstAnswer, NumBits); 4067 } 4068 4069 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4070 // use this information. 4071 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4072 4073 APInt Mask; 4074 if (Known.isNonNegative()) { // sign bit is 0 4075 Mask = Known.Zero; 4076 } else if (Known.isNegative()) { // sign bit is 1; 4077 Mask = Known.One; 4078 } else { 4079 // Nothing known. 4080 return FirstAnswer; 4081 } 4082 4083 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4084 // the number of identical bits in the top of the input value. 4085 Mask <<= Mask.getBitWidth()-VTBits; 4086 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4087 } 4088 4089 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4090 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4091 !isa<ConstantSDNode>(Op.getOperand(1))) 4092 return false; 4093 4094 if (Op.getOpcode() == ISD::OR && 4095 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4096 return false; 4097 4098 return true; 4099 } 4100 4101 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4102 // If we're told that NaNs won't happen, assume they won't. 4103 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4104 return true; 4105 4106 if (Depth >= MaxRecursionDepth) 4107 return false; // Limit search depth. 4108 4109 // TODO: Handle vectors. 4110 // If the value is a constant, we can obviously see if it is a NaN or not. 4111 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4112 return !C->getValueAPF().isNaN() || 4113 (SNaN && !C->getValueAPF().isSignaling()); 4114 } 4115 4116 unsigned Opcode = Op.getOpcode(); 4117 switch (Opcode) { 4118 case ISD::FADD: 4119 case ISD::FSUB: 4120 case ISD::FMUL: 4121 case ISD::FDIV: 4122 case ISD::FREM: 4123 case ISD::FSIN: 4124 case ISD::FCOS: { 4125 if (SNaN) 4126 return true; 4127 // TODO: Need isKnownNeverInfinity 4128 return false; 4129 } 4130 case ISD::FCANONICALIZE: 4131 case ISD::FEXP: 4132 case ISD::FEXP2: 4133 case ISD::FTRUNC: 4134 case ISD::FFLOOR: 4135 case ISD::FCEIL: 4136 case ISD::FROUND: 4137 case ISD::FROUNDEVEN: 4138 case ISD::FRINT: 4139 case ISD::FNEARBYINT: { 4140 if (SNaN) 4141 return true; 4142 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4143 } 4144 case ISD::FABS: 4145 case ISD::FNEG: 4146 case ISD::FCOPYSIGN: { 4147 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4148 } 4149 case ISD::SELECT: 4150 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4151 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4152 case ISD::FP_EXTEND: 4153 case ISD::FP_ROUND: { 4154 if (SNaN) 4155 return true; 4156 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4157 } 4158 case ISD::SINT_TO_FP: 4159 case ISD::UINT_TO_FP: 4160 return true; 4161 case ISD::FMA: 4162 case ISD::FMAD: { 4163 if (SNaN) 4164 return true; 4165 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4166 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4167 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4168 } 4169 case ISD::FSQRT: // Need is known positive 4170 case ISD::FLOG: 4171 case ISD::FLOG2: 4172 case ISD::FLOG10: 4173 case ISD::FPOWI: 4174 case ISD::FPOW: { 4175 if (SNaN) 4176 return true; 4177 // TODO: Refine on operand 4178 return false; 4179 } 4180 case ISD::FMINNUM: 4181 case ISD::FMAXNUM: { 4182 // Only one needs to be known not-nan, since it will be returned if the 4183 // other ends up being one. 4184 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4185 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4186 } 4187 case ISD::FMINNUM_IEEE: 4188 case ISD::FMAXNUM_IEEE: { 4189 if (SNaN) 4190 return true; 4191 // This can return a NaN if either operand is an sNaN, or if both operands 4192 // are NaN. 4193 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4194 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4195 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4196 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4197 } 4198 case ISD::FMINIMUM: 4199 case ISD::FMAXIMUM: { 4200 // TODO: Does this quiet or return the origina NaN as-is? 4201 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4202 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4203 } 4204 case ISD::EXTRACT_VECTOR_ELT: { 4205 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4206 } 4207 default: 4208 if (Opcode >= ISD::BUILTIN_OP_END || 4209 Opcode == ISD::INTRINSIC_WO_CHAIN || 4210 Opcode == ISD::INTRINSIC_W_CHAIN || 4211 Opcode == ISD::INTRINSIC_VOID) { 4212 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4213 } 4214 4215 return false; 4216 } 4217 } 4218 4219 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4220 assert(Op.getValueType().isFloatingPoint() && 4221 "Floating point type expected"); 4222 4223 // If the value is a constant, we can obviously see if it is a zero or not. 4224 // TODO: Add BuildVector support. 4225 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4226 return !C->isZero(); 4227 return false; 4228 } 4229 4230 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4231 assert(!Op.getValueType().isFloatingPoint() && 4232 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4233 4234 // If the value is a constant, we can obviously see if it is a zero or not. 4235 if (ISD::matchUnaryPredicate( 4236 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4237 return true; 4238 4239 // TODO: Recognize more cases here. 4240 switch (Op.getOpcode()) { 4241 default: break; 4242 case ISD::OR: 4243 if (isKnownNeverZero(Op.getOperand(1)) || 4244 isKnownNeverZero(Op.getOperand(0))) 4245 return true; 4246 break; 4247 } 4248 4249 return false; 4250 } 4251 4252 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4253 // Check the obvious case. 4254 if (A == B) return true; 4255 4256 // For for negative and positive zero. 4257 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4258 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4259 if (CA->isZero() && CB->isZero()) return true; 4260 4261 // Otherwise they may not be equal. 4262 return false; 4263 } 4264 4265 // FIXME: unify with llvm::haveNoCommonBitsSet. 4266 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4267 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4268 assert(A.getValueType() == B.getValueType() && 4269 "Values must have the same type"); 4270 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue(); 4271 } 4272 4273 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4274 ArrayRef<SDValue> Ops, 4275 SelectionDAG &DAG) { 4276 int NumOps = Ops.size(); 4277 assert(NumOps != 0 && "Can't build an empty vector!"); 4278 assert(!VT.isScalableVector() && 4279 "BUILD_VECTOR cannot be used with scalable types"); 4280 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4281 "Incorrect element count in BUILD_VECTOR!"); 4282 4283 // BUILD_VECTOR of UNDEFs is UNDEF. 4284 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4285 return DAG.getUNDEF(VT); 4286 4287 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4288 SDValue IdentitySrc; 4289 bool IsIdentity = true; 4290 for (int i = 0; i != NumOps; ++i) { 4291 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4292 Ops[i].getOperand(0).getValueType() != VT || 4293 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4294 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4295 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4296 IsIdentity = false; 4297 break; 4298 } 4299 IdentitySrc = Ops[i].getOperand(0); 4300 } 4301 if (IsIdentity) 4302 return IdentitySrc; 4303 4304 return SDValue(); 4305 } 4306 4307 /// Try to simplify vector concatenation to an input value, undef, or build 4308 /// vector. 4309 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4310 ArrayRef<SDValue> Ops, 4311 SelectionDAG &DAG) { 4312 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4313 assert(llvm::all_of(Ops, 4314 [Ops](SDValue Op) { 4315 return Ops[0].getValueType() == Op.getValueType(); 4316 }) && 4317 "Concatenation of vectors with inconsistent value types!"); 4318 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4319 VT.getVectorElementCount() && 4320 "Incorrect element count in vector concatenation!"); 4321 4322 if (Ops.size() == 1) 4323 return Ops[0]; 4324 4325 // Concat of UNDEFs is UNDEF. 4326 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4327 return DAG.getUNDEF(VT); 4328 4329 // Scan the operands and look for extract operations from a single source 4330 // that correspond to insertion at the same location via this concatenation: 4331 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4332 SDValue IdentitySrc; 4333 bool IsIdentity = true; 4334 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4335 SDValue Op = Ops[i]; 4336 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4337 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4338 Op.getOperand(0).getValueType() != VT || 4339 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4340 Op.getConstantOperandVal(1) != IdentityIndex) { 4341 IsIdentity = false; 4342 break; 4343 } 4344 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4345 "Unexpected identity source vector for concat of extracts"); 4346 IdentitySrc = Op.getOperand(0); 4347 } 4348 if (IsIdentity) { 4349 assert(IdentitySrc && "Failed to set source vector of extracts"); 4350 return IdentitySrc; 4351 } 4352 4353 // The code below this point is only designed to work for fixed width 4354 // vectors, so we bail out for now. 4355 if (VT.isScalableVector()) 4356 return SDValue(); 4357 4358 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4359 // simplified to one big BUILD_VECTOR. 4360 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4361 EVT SVT = VT.getScalarType(); 4362 SmallVector<SDValue, 16> Elts; 4363 for (SDValue Op : Ops) { 4364 EVT OpVT = Op.getValueType(); 4365 if (Op.isUndef()) 4366 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4367 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4368 Elts.append(Op->op_begin(), Op->op_end()); 4369 else 4370 return SDValue(); 4371 } 4372 4373 // BUILD_VECTOR requires all inputs to be of the same type, find the 4374 // maximum type and extend them all. 4375 for (SDValue Op : Elts) 4376 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4377 4378 if (SVT.bitsGT(VT.getScalarType())) { 4379 for (SDValue &Op : Elts) { 4380 if (Op.isUndef()) 4381 Op = DAG.getUNDEF(SVT); 4382 else 4383 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4384 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4385 : DAG.getSExtOrTrunc(Op, DL, SVT); 4386 } 4387 } 4388 4389 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4390 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4391 return V; 4392 } 4393 4394 /// Gets or creates the specified node. 4395 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4396 FoldingSetNodeID ID; 4397 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4398 void *IP = nullptr; 4399 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4400 return SDValue(E, 0); 4401 4402 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4403 getVTList(VT)); 4404 CSEMap.InsertNode(N, IP); 4405 4406 InsertNode(N); 4407 SDValue V = SDValue(N, 0); 4408 NewSDValueDbgMsg(V, "Creating new node: ", this); 4409 return V; 4410 } 4411 4412 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4413 SDValue Operand) { 4414 SDNodeFlags Flags; 4415 if (Inserter) 4416 Flags = Inserter->getFlags(); 4417 return getNode(Opcode, DL, VT, Operand, Flags); 4418 } 4419 4420 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4421 SDValue Operand, const SDNodeFlags Flags) { 4422 // Constant fold unary operations with an integer constant operand. Even 4423 // opaque constant will be folded, because the folding of unary operations 4424 // doesn't create new constants with different values. Nevertheless, the 4425 // opaque flag is preserved during folding to prevent future folding with 4426 // other constants. 4427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4428 const APInt &Val = C->getAPIntValue(); 4429 switch (Opcode) { 4430 default: break; 4431 case ISD::SIGN_EXTEND: 4432 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4433 C->isTargetOpcode(), C->isOpaque()); 4434 case ISD::TRUNCATE: 4435 if (C->isOpaque()) 4436 break; 4437 LLVM_FALLTHROUGH; 4438 case ISD::ANY_EXTEND: 4439 case ISD::ZERO_EXTEND: 4440 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4441 C->isTargetOpcode(), C->isOpaque()); 4442 case ISD::UINT_TO_FP: 4443 case ISD::SINT_TO_FP: { 4444 APFloat apf(EVTToAPFloatSemantics(VT), 4445 APInt::getNullValue(VT.getSizeInBits())); 4446 (void)apf.convertFromAPInt(Val, 4447 Opcode==ISD::SINT_TO_FP, 4448 APFloat::rmNearestTiesToEven); 4449 return getConstantFP(apf, DL, VT); 4450 } 4451 case ISD::BITCAST: 4452 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4453 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4454 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4455 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4456 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4457 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4458 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4459 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4460 break; 4461 case ISD::ABS: 4462 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4463 C->isOpaque()); 4464 case ISD::BITREVERSE: 4465 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4466 C->isOpaque()); 4467 case ISD::BSWAP: 4468 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4469 C->isOpaque()); 4470 case ISD::CTPOP: 4471 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4472 C->isOpaque()); 4473 case ISD::CTLZ: 4474 case ISD::CTLZ_ZERO_UNDEF: 4475 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4476 C->isOpaque()); 4477 case ISD::CTTZ: 4478 case ISD::CTTZ_ZERO_UNDEF: 4479 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4480 C->isOpaque()); 4481 case ISD::FP16_TO_FP: { 4482 bool Ignored; 4483 APFloat FPV(APFloat::IEEEhalf(), 4484 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4485 4486 // This can return overflow, underflow, or inexact; we don't care. 4487 // FIXME need to be more flexible about rounding mode. 4488 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4489 APFloat::rmNearestTiesToEven, &Ignored); 4490 return getConstantFP(FPV, DL, VT); 4491 } 4492 } 4493 } 4494 4495 // Constant fold unary operations with a floating point constant operand. 4496 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4497 APFloat V = C->getValueAPF(); // make copy 4498 switch (Opcode) { 4499 case ISD::FNEG: 4500 V.changeSign(); 4501 return getConstantFP(V, DL, VT); 4502 case ISD::FABS: 4503 V.clearSign(); 4504 return getConstantFP(V, DL, VT); 4505 case ISD::FCEIL: { 4506 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4507 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4508 return getConstantFP(V, DL, VT); 4509 break; 4510 } 4511 case ISD::FTRUNC: { 4512 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4513 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4514 return getConstantFP(V, DL, VT); 4515 break; 4516 } 4517 case ISD::FFLOOR: { 4518 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4519 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4520 return getConstantFP(V, DL, VT); 4521 break; 4522 } 4523 case ISD::FP_EXTEND: { 4524 bool ignored; 4525 // This can return overflow, underflow, or inexact; we don't care. 4526 // FIXME need to be more flexible about rounding mode. 4527 (void)V.convert(EVTToAPFloatSemantics(VT), 4528 APFloat::rmNearestTiesToEven, &ignored); 4529 return getConstantFP(V, DL, VT); 4530 } 4531 case ISD::FP_TO_SINT: 4532 case ISD::FP_TO_UINT: { 4533 bool ignored; 4534 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4535 // FIXME need to be more flexible about rounding mode. 4536 APFloat::opStatus s = 4537 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4538 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4539 break; 4540 return getConstant(IntVal, DL, VT); 4541 } 4542 case ISD::BITCAST: 4543 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4544 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4545 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4546 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4547 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4548 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4549 break; 4550 case ISD::FP_TO_FP16: { 4551 bool Ignored; 4552 // This can return overflow, underflow, or inexact; we don't care. 4553 // FIXME need to be more flexible about rounding mode. 4554 (void)V.convert(APFloat::IEEEhalf(), 4555 APFloat::rmNearestTiesToEven, &Ignored); 4556 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4557 } 4558 } 4559 } 4560 4561 // Constant fold unary operations with a vector integer or float operand. 4562 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 4563 if (BV->isConstant()) { 4564 switch (Opcode) { 4565 default: 4566 // FIXME: Entirely reasonable to perform folding of other unary 4567 // operations here as the need arises. 4568 break; 4569 case ISD::FNEG: 4570 case ISD::FABS: 4571 case ISD::FCEIL: 4572 case ISD::FTRUNC: 4573 case ISD::FFLOOR: 4574 case ISD::FP_EXTEND: 4575 case ISD::FP_TO_SINT: 4576 case ISD::FP_TO_UINT: 4577 case ISD::TRUNCATE: 4578 case ISD::ANY_EXTEND: 4579 case ISD::ZERO_EXTEND: 4580 case ISD::SIGN_EXTEND: 4581 case ISD::UINT_TO_FP: 4582 case ISD::SINT_TO_FP: 4583 case ISD::ABS: 4584 case ISD::BITREVERSE: 4585 case ISD::BSWAP: 4586 case ISD::CTLZ: 4587 case ISD::CTLZ_ZERO_UNDEF: 4588 case ISD::CTTZ: 4589 case ISD::CTTZ_ZERO_UNDEF: 4590 case ISD::CTPOP: { 4591 SDValue Ops = { Operand }; 4592 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4593 return Fold; 4594 } 4595 } 4596 } 4597 } 4598 4599 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4600 switch (Opcode) { 4601 case ISD::FREEZE: 4602 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4603 break; 4604 case ISD::TokenFactor: 4605 case ISD::MERGE_VALUES: 4606 case ISD::CONCAT_VECTORS: 4607 return Operand; // Factor, merge or concat of one node? No need. 4608 case ISD::BUILD_VECTOR: { 4609 // Attempt to simplify BUILD_VECTOR. 4610 SDValue Ops[] = {Operand}; 4611 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4612 return V; 4613 break; 4614 } 4615 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4616 case ISD::FP_EXTEND: 4617 assert(VT.isFloatingPoint() && 4618 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4619 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4620 assert((!VT.isVector() || 4621 VT.getVectorElementCount() == 4622 Operand.getValueType().getVectorElementCount()) && 4623 "Vector element count mismatch!"); 4624 assert(Operand.getValueType().bitsLT(VT) && 4625 "Invalid fpext node, dst < src!"); 4626 if (Operand.isUndef()) 4627 return getUNDEF(VT); 4628 break; 4629 case ISD::FP_TO_SINT: 4630 case ISD::FP_TO_UINT: 4631 if (Operand.isUndef()) 4632 return getUNDEF(VT); 4633 break; 4634 case ISD::SINT_TO_FP: 4635 case ISD::UINT_TO_FP: 4636 // [us]itofp(undef) = 0, because the result value is bounded. 4637 if (Operand.isUndef()) 4638 return getConstantFP(0.0, DL, VT); 4639 break; 4640 case ISD::SIGN_EXTEND: 4641 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4642 "Invalid SIGN_EXTEND!"); 4643 assert(VT.isVector() == Operand.getValueType().isVector() && 4644 "SIGN_EXTEND result type type should be vector iff the operand " 4645 "type is vector!"); 4646 if (Operand.getValueType() == VT) return Operand; // noop extension 4647 assert((!VT.isVector() || 4648 VT.getVectorElementCount() == 4649 Operand.getValueType().getVectorElementCount()) && 4650 "Vector element count mismatch!"); 4651 assert(Operand.getValueType().bitsLT(VT) && 4652 "Invalid sext node, dst < src!"); 4653 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4654 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4655 else if (OpOpcode == ISD::UNDEF) 4656 // sext(undef) = 0, because the top bits will all be the same. 4657 return getConstant(0, DL, VT); 4658 break; 4659 case ISD::ZERO_EXTEND: 4660 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4661 "Invalid ZERO_EXTEND!"); 4662 assert(VT.isVector() == Operand.getValueType().isVector() && 4663 "ZERO_EXTEND result type type should be vector iff the operand " 4664 "type is vector!"); 4665 if (Operand.getValueType() == VT) return Operand; // noop extension 4666 assert((!VT.isVector() || 4667 VT.getVectorElementCount() == 4668 Operand.getValueType().getVectorElementCount()) && 4669 "Vector element count mismatch!"); 4670 assert(Operand.getValueType().bitsLT(VT) && 4671 "Invalid zext node, dst < src!"); 4672 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4673 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4674 else if (OpOpcode == ISD::UNDEF) 4675 // zext(undef) = 0, because the top bits will be zero. 4676 return getConstant(0, DL, VT); 4677 break; 4678 case ISD::ANY_EXTEND: 4679 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4680 "Invalid ANY_EXTEND!"); 4681 assert(VT.isVector() == Operand.getValueType().isVector() && 4682 "ANY_EXTEND result type type should be vector iff the operand " 4683 "type is vector!"); 4684 if (Operand.getValueType() == VT) return Operand; // noop extension 4685 assert((!VT.isVector() || 4686 VT.getVectorElementCount() == 4687 Operand.getValueType().getVectorElementCount()) && 4688 "Vector element count mismatch!"); 4689 assert(Operand.getValueType().bitsLT(VT) && 4690 "Invalid anyext node, dst < src!"); 4691 4692 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4693 OpOpcode == ISD::ANY_EXTEND) 4694 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4695 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4696 else if (OpOpcode == ISD::UNDEF) 4697 return getUNDEF(VT); 4698 4699 // (ext (trunc x)) -> x 4700 if (OpOpcode == ISD::TRUNCATE) { 4701 SDValue OpOp = Operand.getOperand(0); 4702 if (OpOp.getValueType() == VT) { 4703 transferDbgValues(Operand, OpOp); 4704 return OpOp; 4705 } 4706 } 4707 break; 4708 case ISD::TRUNCATE: 4709 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4710 "Invalid TRUNCATE!"); 4711 assert(VT.isVector() == Operand.getValueType().isVector() && 4712 "TRUNCATE result type type should be vector iff the operand " 4713 "type is vector!"); 4714 if (Operand.getValueType() == VT) return Operand; // noop truncate 4715 assert((!VT.isVector() || 4716 VT.getVectorElementCount() == 4717 Operand.getValueType().getVectorElementCount()) && 4718 "Vector element count mismatch!"); 4719 assert(Operand.getValueType().bitsGT(VT) && 4720 "Invalid truncate node, src < dst!"); 4721 if (OpOpcode == ISD::TRUNCATE) 4722 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4723 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4724 OpOpcode == ISD::ANY_EXTEND) { 4725 // If the source is smaller than the dest, we still need an extend. 4726 if (Operand.getOperand(0).getValueType().getScalarType() 4727 .bitsLT(VT.getScalarType())) 4728 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4729 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4730 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4731 return Operand.getOperand(0); 4732 } 4733 if (OpOpcode == ISD::UNDEF) 4734 return getUNDEF(VT); 4735 break; 4736 case ISD::ANY_EXTEND_VECTOR_INREG: 4737 case ISD::ZERO_EXTEND_VECTOR_INREG: 4738 case ISD::SIGN_EXTEND_VECTOR_INREG: 4739 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4740 assert(Operand.getValueType().bitsLE(VT) && 4741 "The input must be the same size or smaller than the result."); 4742 assert(VT.getVectorNumElements() < 4743 Operand.getValueType().getVectorNumElements() && 4744 "The destination vector type must have fewer lanes than the input."); 4745 break; 4746 case ISD::ABS: 4747 assert(VT.isInteger() && VT == Operand.getValueType() && 4748 "Invalid ABS!"); 4749 if (OpOpcode == ISD::UNDEF) 4750 return getUNDEF(VT); 4751 break; 4752 case ISD::BSWAP: 4753 assert(VT.isInteger() && VT == Operand.getValueType() && 4754 "Invalid BSWAP!"); 4755 assert((VT.getScalarSizeInBits() % 16 == 0) && 4756 "BSWAP types must be a multiple of 16 bits!"); 4757 if (OpOpcode == ISD::UNDEF) 4758 return getUNDEF(VT); 4759 break; 4760 case ISD::BITREVERSE: 4761 assert(VT.isInteger() && VT == Operand.getValueType() && 4762 "Invalid BITREVERSE!"); 4763 if (OpOpcode == ISD::UNDEF) 4764 return getUNDEF(VT); 4765 break; 4766 case ISD::BITCAST: 4767 // Basic sanity checking. 4768 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4769 "Cannot BITCAST between types of different sizes!"); 4770 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4771 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4772 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4773 if (OpOpcode == ISD::UNDEF) 4774 return getUNDEF(VT); 4775 break; 4776 case ISD::SCALAR_TO_VECTOR: 4777 assert(VT.isVector() && !Operand.getValueType().isVector() && 4778 (VT.getVectorElementType() == Operand.getValueType() || 4779 (VT.getVectorElementType().isInteger() && 4780 Operand.getValueType().isInteger() && 4781 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4782 "Illegal SCALAR_TO_VECTOR node!"); 4783 if (OpOpcode == ISD::UNDEF) 4784 return getUNDEF(VT); 4785 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4786 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4787 isa<ConstantSDNode>(Operand.getOperand(1)) && 4788 Operand.getConstantOperandVal(1) == 0 && 4789 Operand.getOperand(0).getValueType() == VT) 4790 return Operand.getOperand(0); 4791 break; 4792 case ISD::FNEG: 4793 // Negation of an unknown bag of bits is still completely undefined. 4794 if (OpOpcode == ISD::UNDEF) 4795 return getUNDEF(VT); 4796 4797 if (OpOpcode == ISD::FNEG) // --X -> X 4798 return Operand.getOperand(0); 4799 break; 4800 case ISD::FABS: 4801 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4802 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4803 break; 4804 case ISD::VSCALE: 4805 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4806 break; 4807 case ISD::CTPOP: 4808 if (Operand.getValueType().getScalarType() == MVT::i1) 4809 return Operand; 4810 break; 4811 case ISD::CTLZ: 4812 case ISD::CTTZ: 4813 if (Operand.getValueType().getScalarType() == MVT::i1) 4814 return getNOT(DL, Operand, Operand.getValueType()); 4815 break; 4816 case ISD::VECREDUCE_SMIN: 4817 case ISD::VECREDUCE_UMAX: 4818 if (Operand.getValueType().getScalarType() == MVT::i1) 4819 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 4820 break; 4821 case ISD::VECREDUCE_SMAX: 4822 case ISD::VECREDUCE_UMIN: 4823 if (Operand.getValueType().getScalarType() == MVT::i1) 4824 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 4825 break; 4826 } 4827 4828 SDNode *N; 4829 SDVTList VTs = getVTList(VT); 4830 SDValue Ops[] = {Operand}; 4831 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 4832 FoldingSetNodeID ID; 4833 AddNodeIDNode(ID, Opcode, VTs, Ops); 4834 void *IP = nullptr; 4835 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 4836 E->intersectFlagsWith(Flags); 4837 return SDValue(E, 0); 4838 } 4839 4840 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4841 N->setFlags(Flags); 4842 createOperands(N, Ops); 4843 CSEMap.InsertNode(N, IP); 4844 } else { 4845 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4846 createOperands(N, Ops); 4847 } 4848 4849 InsertNode(N); 4850 SDValue V = SDValue(N, 0); 4851 NewSDValueDbgMsg(V, "Creating new node: ", this); 4852 return V; 4853 } 4854 4855 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 4856 const APInt &C2) { 4857 switch (Opcode) { 4858 case ISD::ADD: return C1 + C2; 4859 case ISD::SUB: return C1 - C2; 4860 case ISD::MUL: return C1 * C2; 4861 case ISD::AND: return C1 & C2; 4862 case ISD::OR: return C1 | C2; 4863 case ISD::XOR: return C1 ^ C2; 4864 case ISD::SHL: return C1 << C2; 4865 case ISD::SRL: return C1.lshr(C2); 4866 case ISD::SRA: return C1.ashr(C2); 4867 case ISD::ROTL: return C1.rotl(C2); 4868 case ISD::ROTR: return C1.rotr(C2); 4869 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 4870 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 4871 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 4872 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 4873 case ISD::SADDSAT: return C1.sadd_sat(C2); 4874 case ISD::UADDSAT: return C1.uadd_sat(C2); 4875 case ISD::SSUBSAT: return C1.ssub_sat(C2); 4876 case ISD::USUBSAT: return C1.usub_sat(C2); 4877 case ISD::UDIV: 4878 if (!C2.getBoolValue()) 4879 break; 4880 return C1.udiv(C2); 4881 case ISD::UREM: 4882 if (!C2.getBoolValue()) 4883 break; 4884 return C1.urem(C2); 4885 case ISD::SDIV: 4886 if (!C2.getBoolValue()) 4887 break; 4888 return C1.sdiv(C2); 4889 case ISD::SREM: 4890 if (!C2.getBoolValue()) 4891 break; 4892 return C1.srem(C2); 4893 } 4894 return llvm::None; 4895 } 4896 4897 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 4898 const GlobalAddressSDNode *GA, 4899 const SDNode *N2) { 4900 if (GA->getOpcode() != ISD::GlobalAddress) 4901 return SDValue(); 4902 if (!TLI->isOffsetFoldingLegal(GA)) 4903 return SDValue(); 4904 auto *C2 = dyn_cast<ConstantSDNode>(N2); 4905 if (!C2) 4906 return SDValue(); 4907 int64_t Offset = C2->getSExtValue(); 4908 switch (Opcode) { 4909 case ISD::ADD: break; 4910 case ISD::SUB: Offset = -uint64_t(Offset); break; 4911 default: return SDValue(); 4912 } 4913 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 4914 GA->getOffset() + uint64_t(Offset)); 4915 } 4916 4917 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 4918 switch (Opcode) { 4919 case ISD::SDIV: 4920 case ISD::UDIV: 4921 case ISD::SREM: 4922 case ISD::UREM: { 4923 // If a divisor is zero/undef or any element of a divisor vector is 4924 // zero/undef, the whole op is undef. 4925 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 4926 SDValue Divisor = Ops[1]; 4927 if (Divisor.isUndef() || isNullConstant(Divisor)) 4928 return true; 4929 4930 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 4931 llvm::any_of(Divisor->op_values(), 4932 [](SDValue V) { return V.isUndef() || 4933 isNullConstant(V); }); 4934 // TODO: Handle signed overflow. 4935 } 4936 // TODO: Handle oversized shifts. 4937 default: 4938 return false; 4939 } 4940 } 4941 4942 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 4943 EVT VT, ArrayRef<SDValue> Ops) { 4944 // If the opcode is a target-specific ISD node, there's nothing we can 4945 // do here and the operand rules may not line up with the below, so 4946 // bail early. 4947 if (Opcode >= ISD::BUILTIN_OP_END) 4948 return SDValue(); 4949 4950 // For now, the array Ops should only contain two values. 4951 // This enforcement will be removed once this function is merged with 4952 // FoldConstantVectorArithmetic 4953 if (Ops.size() != 2) 4954 return SDValue(); 4955 4956 if (isUndef(Opcode, Ops)) 4957 return getUNDEF(VT); 4958 4959 SDNode *N1 = Ops[0].getNode(); 4960 SDNode *N2 = Ops[1].getNode(); 4961 4962 // Handle the case of two scalars. 4963 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 4964 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 4965 if (C1->isOpaque() || C2->isOpaque()) 4966 return SDValue(); 4967 4968 Optional<APInt> FoldAttempt = 4969 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 4970 if (!FoldAttempt) 4971 return SDValue(); 4972 4973 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 4974 assert((!Folded || !VT.isVector()) && 4975 "Can't fold vectors ops with scalar operands"); 4976 return Folded; 4977 } 4978 } 4979 4980 // fold (add Sym, c) -> Sym+c 4981 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 4982 return FoldSymbolOffset(Opcode, VT, GA, N2); 4983 if (TLI->isCommutativeBinOp(Opcode)) 4984 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 4985 return FoldSymbolOffset(Opcode, VT, GA, N1); 4986 4987 // TODO: All the folds below are performed lane-by-lane and assume a fixed 4988 // vector width, however we should be able to do constant folds involving 4989 // splat vector nodes too. 4990 if (VT.isScalableVector()) 4991 return SDValue(); 4992 4993 // For fixed width vectors, extract each constant element and fold them 4994 // individually. Either input may be an undef value. 4995 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 4996 if (!BV1 && !N1->isUndef()) 4997 return SDValue(); 4998 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 4999 if (!BV2 && !N2->isUndef()) 5000 return SDValue(); 5001 // If both operands are undef, that's handled the same way as scalars. 5002 if (!BV1 && !BV2) 5003 return SDValue(); 5004 5005 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) && 5006 "Vector binop with different number of elements in operands?"); 5007 5008 EVT SVT = VT.getScalarType(); 5009 EVT LegalSVT = SVT; 5010 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5011 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5012 if (LegalSVT.bitsLT(SVT)) 5013 return SDValue(); 5014 } 5015 SmallVector<SDValue, 4> Outputs; 5016 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands(); 5017 for (unsigned I = 0; I != NumOps; ++I) { 5018 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT); 5019 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT); 5020 if (SVT.isInteger()) { 5021 if (V1->getValueType(0).bitsGT(SVT)) 5022 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5023 if (V2->getValueType(0).bitsGT(SVT)) 5024 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5025 } 5026 5027 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 5028 return SDValue(); 5029 5030 // Fold one vector element. 5031 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5032 if (LegalSVT != SVT) 5033 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5034 5035 // Scalar folding only succeeded if the result is a constant or UNDEF. 5036 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5037 ScalarResult.getOpcode() != ISD::ConstantFP) 5038 return SDValue(); 5039 Outputs.push_back(ScalarResult); 5040 } 5041 5042 assert(VT.getVectorNumElements() == Outputs.size() && 5043 "Vector size mismatch!"); 5044 5045 // We may have a vector type but a scalar result. Create a splat. 5046 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 5047 5048 // Build a big vector out of the scalar elements we generated. 5049 return getBuildVector(VT, SDLoc(), Outputs); 5050 } 5051 5052 // TODO: Merge with FoldConstantArithmetic 5053 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5054 const SDLoc &DL, EVT VT, 5055 ArrayRef<SDValue> Ops, 5056 const SDNodeFlags Flags) { 5057 // If the opcode is a target-specific ISD node, there's nothing we can 5058 // do here and the operand rules may not line up with the below, so 5059 // bail early. 5060 if (Opcode >= ISD::BUILTIN_OP_END) 5061 return SDValue(); 5062 5063 if (isUndef(Opcode, Ops)) 5064 return getUNDEF(VT); 5065 5066 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5067 if (!VT.isVector()) 5068 return SDValue(); 5069 5070 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5071 // vector width, however we should be able to do constant folds involving 5072 // splat vector nodes too. 5073 if (VT.isScalableVector()) 5074 return SDValue(); 5075 5076 // From this point onwards all vectors are assumed to be fixed width. 5077 unsigned NumElts = VT.getVectorNumElements(); 5078 5079 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5080 return !Op.getValueType().isVector() || 5081 Op.getValueType().getVectorNumElements() == NumElts; 5082 }; 5083 5084 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5085 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5086 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5087 (BV && BV->isConstant()); 5088 }; 5089 5090 // All operands must be vector types with the same number of elements as 5091 // the result type and must be either UNDEF or a build vector of constant 5092 // or UNDEF scalars. 5093 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5094 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5095 return SDValue(); 5096 5097 // If we are comparing vectors, then the result needs to be a i1 boolean 5098 // that is then sign-extended back to the legal result type. 5099 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5100 5101 // Find legal integer scalar type for constant promotion and 5102 // ensure that its scalar size is at least as large as source. 5103 EVT LegalSVT = VT.getScalarType(); 5104 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5105 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5106 if (LegalSVT.bitsLT(VT.getScalarType())) 5107 return SDValue(); 5108 } 5109 5110 // Constant fold each scalar lane separately. 5111 SmallVector<SDValue, 4> ScalarResults; 5112 for (unsigned i = 0; i != NumElts; i++) { 5113 SmallVector<SDValue, 4> ScalarOps; 5114 for (SDValue Op : Ops) { 5115 EVT InSVT = Op.getValueType().getScalarType(); 5116 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5117 if (!InBV) { 5118 // We've checked that this is UNDEF or a constant of some kind. 5119 if (Op.isUndef()) 5120 ScalarOps.push_back(getUNDEF(InSVT)); 5121 else 5122 ScalarOps.push_back(Op); 5123 continue; 5124 } 5125 5126 SDValue ScalarOp = InBV->getOperand(i); 5127 EVT ScalarVT = ScalarOp.getValueType(); 5128 5129 // Build vector (integer) scalar operands may need implicit 5130 // truncation - do this before constant folding. 5131 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5132 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5133 5134 ScalarOps.push_back(ScalarOp); 5135 } 5136 5137 // Constant fold the scalar operands. 5138 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5139 5140 // Legalize the (integer) scalar constant if necessary. 5141 if (LegalSVT != SVT) 5142 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5143 5144 // Scalar folding only succeeded if the result is a constant or UNDEF. 5145 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5146 ScalarResult.getOpcode() != ISD::ConstantFP) 5147 return SDValue(); 5148 ScalarResults.push_back(ScalarResult); 5149 } 5150 5151 SDValue V = getBuildVector(VT, DL, ScalarResults); 5152 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5153 return V; 5154 } 5155 5156 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5157 EVT VT, SDValue N1, SDValue N2) { 5158 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5159 // should. That will require dealing with a potentially non-default 5160 // rounding mode, checking the "opStatus" return value from the APFloat 5161 // math calculations, and possibly other variations. 5162 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5163 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5164 if (N1CFP && N2CFP) { 5165 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5166 switch (Opcode) { 5167 case ISD::FADD: 5168 C1.add(C2, APFloat::rmNearestTiesToEven); 5169 return getConstantFP(C1, DL, VT); 5170 case ISD::FSUB: 5171 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5172 return getConstantFP(C1, DL, VT); 5173 case ISD::FMUL: 5174 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5175 return getConstantFP(C1, DL, VT); 5176 case ISD::FDIV: 5177 C1.divide(C2, APFloat::rmNearestTiesToEven); 5178 return getConstantFP(C1, DL, VT); 5179 case ISD::FREM: 5180 C1.mod(C2); 5181 return getConstantFP(C1, DL, VT); 5182 case ISD::FCOPYSIGN: 5183 C1.copySign(C2); 5184 return getConstantFP(C1, DL, VT); 5185 default: break; 5186 } 5187 } 5188 if (N1CFP && Opcode == ISD::FP_ROUND) { 5189 APFloat C1 = N1CFP->getValueAPF(); // make copy 5190 bool Unused; 5191 // This can return overflow, underflow, or inexact; we don't care. 5192 // FIXME need to be more flexible about rounding mode. 5193 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5194 &Unused); 5195 return getConstantFP(C1, DL, VT); 5196 } 5197 5198 switch (Opcode) { 5199 case ISD::FSUB: 5200 // -0.0 - undef --> undef (consistent with "fneg undef") 5201 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5202 return getUNDEF(VT); 5203 LLVM_FALLTHROUGH; 5204 5205 case ISD::FADD: 5206 case ISD::FMUL: 5207 case ISD::FDIV: 5208 case ISD::FREM: 5209 // If both operands are undef, the result is undef. If 1 operand is undef, 5210 // the result is NaN. This should match the behavior of the IR optimizer. 5211 if (N1.isUndef() && N2.isUndef()) 5212 return getUNDEF(VT); 5213 if (N1.isUndef() || N2.isUndef()) 5214 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5215 } 5216 return SDValue(); 5217 } 5218 5219 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5220 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5221 5222 // There's no need to assert on a byte-aligned pointer. All pointers are at 5223 // least byte aligned. 5224 if (A == Align(1)) 5225 return Val; 5226 5227 FoldingSetNodeID ID; 5228 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5229 ID.AddInteger(A.value()); 5230 5231 void *IP = nullptr; 5232 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5233 return SDValue(E, 0); 5234 5235 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5236 Val.getValueType(), A); 5237 createOperands(N, {Val}); 5238 5239 CSEMap.InsertNode(N, IP); 5240 InsertNode(N); 5241 5242 SDValue V(N, 0); 5243 NewSDValueDbgMsg(V, "Creating new node: ", this); 5244 return V; 5245 } 5246 5247 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5248 SDValue N1, SDValue N2) { 5249 SDNodeFlags Flags; 5250 if (Inserter) 5251 Flags = Inserter->getFlags(); 5252 return getNode(Opcode, DL, VT, N1, N2, Flags); 5253 } 5254 5255 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5256 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5258 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5259 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5260 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5261 5262 // Canonicalize constant to RHS if commutative. 5263 if (TLI->isCommutativeBinOp(Opcode)) { 5264 if (N1C && !N2C) { 5265 std::swap(N1C, N2C); 5266 std::swap(N1, N2); 5267 } else if (N1CFP && !N2CFP) { 5268 std::swap(N1CFP, N2CFP); 5269 std::swap(N1, N2); 5270 } 5271 } 5272 5273 switch (Opcode) { 5274 default: break; 5275 case ISD::TokenFactor: 5276 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5277 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5278 // Fold trivial token factors. 5279 if (N1.getOpcode() == ISD::EntryToken) return N2; 5280 if (N2.getOpcode() == ISD::EntryToken) return N1; 5281 if (N1 == N2) return N1; 5282 break; 5283 case ISD::BUILD_VECTOR: { 5284 // Attempt to simplify BUILD_VECTOR. 5285 SDValue Ops[] = {N1, N2}; 5286 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5287 return V; 5288 break; 5289 } 5290 case ISD::CONCAT_VECTORS: { 5291 SDValue Ops[] = {N1, N2}; 5292 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5293 return V; 5294 break; 5295 } 5296 case ISD::AND: 5297 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5298 assert(N1.getValueType() == N2.getValueType() && 5299 N1.getValueType() == VT && "Binary operator types must match!"); 5300 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5301 // worth handling here. 5302 if (N2C && N2C->isNullValue()) 5303 return N2; 5304 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5305 return N1; 5306 break; 5307 case ISD::OR: 5308 case ISD::XOR: 5309 case ISD::ADD: 5310 case ISD::SUB: 5311 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5312 assert(N1.getValueType() == N2.getValueType() && 5313 N1.getValueType() == VT && "Binary operator types must match!"); 5314 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5315 // it's worth handling here. 5316 if (N2C && N2C->isNullValue()) 5317 return N1; 5318 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5319 VT.getVectorElementType() == MVT::i1) 5320 return getNode(ISD::XOR, DL, VT, N1, N2); 5321 break; 5322 case ISD::MUL: 5323 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5324 assert(N1.getValueType() == N2.getValueType() && 5325 N1.getValueType() == VT && "Binary operator types must match!"); 5326 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5327 return getNode(ISD::AND, DL, VT, N1, N2); 5328 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5329 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5330 const APInt &N2CImm = N2C->getAPIntValue(); 5331 return getVScale(DL, VT, MulImm * N2CImm); 5332 } 5333 break; 5334 case ISD::UDIV: 5335 case ISD::UREM: 5336 case ISD::MULHU: 5337 case ISD::MULHS: 5338 case ISD::SDIV: 5339 case ISD::SREM: 5340 case ISD::SADDSAT: 5341 case ISD::SSUBSAT: 5342 case ISD::UADDSAT: 5343 case ISD::USUBSAT: 5344 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5345 assert(N1.getValueType() == N2.getValueType() && 5346 N1.getValueType() == VT && "Binary operator types must match!"); 5347 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5348 // fold (add_sat x, y) -> (or x, y) for bool types. 5349 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5350 return getNode(ISD::OR, DL, VT, N1, N2); 5351 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5352 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5353 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5354 } 5355 break; 5356 case ISD::SMIN: 5357 case ISD::UMAX: 5358 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5359 assert(N1.getValueType() == N2.getValueType() && 5360 N1.getValueType() == VT && "Binary operator types must match!"); 5361 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5362 return getNode(ISD::OR, DL, VT, N1, N2); 5363 break; 5364 case ISD::SMAX: 5365 case ISD::UMIN: 5366 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5367 assert(N1.getValueType() == N2.getValueType() && 5368 N1.getValueType() == VT && "Binary operator types must match!"); 5369 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5370 return getNode(ISD::AND, DL, VT, N1, N2); 5371 break; 5372 case ISD::FADD: 5373 case ISD::FSUB: 5374 case ISD::FMUL: 5375 case ISD::FDIV: 5376 case ISD::FREM: 5377 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5378 assert(N1.getValueType() == N2.getValueType() && 5379 N1.getValueType() == VT && "Binary operator types must match!"); 5380 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5381 return V; 5382 break; 5383 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5384 assert(N1.getValueType() == VT && 5385 N1.getValueType().isFloatingPoint() && 5386 N2.getValueType().isFloatingPoint() && 5387 "Invalid FCOPYSIGN!"); 5388 break; 5389 case ISD::SHL: 5390 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5391 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5392 const APInt &ShiftImm = N2C->getAPIntValue(); 5393 return getVScale(DL, VT, MulImm << ShiftImm); 5394 } 5395 LLVM_FALLTHROUGH; 5396 case ISD::SRA: 5397 case ISD::SRL: 5398 if (SDValue V = simplifyShift(N1, N2)) 5399 return V; 5400 LLVM_FALLTHROUGH; 5401 case ISD::ROTL: 5402 case ISD::ROTR: 5403 assert(VT == N1.getValueType() && 5404 "Shift operators return type must be the same as their first arg"); 5405 assert(VT.isInteger() && N2.getValueType().isInteger() && 5406 "Shifts only work on integers"); 5407 assert((!VT.isVector() || VT == N2.getValueType()) && 5408 "Vector shift amounts must be in the same as their first arg"); 5409 // Verify that the shift amount VT is big enough to hold valid shift 5410 // amounts. This catches things like trying to shift an i1024 value by an 5411 // i8, which is easy to fall into in generic code that uses 5412 // TLI.getShiftAmount(). 5413 assert(N2.getValueType().getScalarSizeInBits() >= 5414 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5415 "Invalid use of small shift amount with oversized value!"); 5416 5417 // Always fold shifts of i1 values so the code generator doesn't need to 5418 // handle them. Since we know the size of the shift has to be less than the 5419 // size of the value, the shift/rotate count is guaranteed to be zero. 5420 if (VT == MVT::i1) 5421 return N1; 5422 if (N2C && N2C->isNullValue()) 5423 return N1; 5424 break; 5425 case ISD::FP_ROUND: 5426 assert(VT.isFloatingPoint() && 5427 N1.getValueType().isFloatingPoint() && 5428 VT.bitsLE(N1.getValueType()) && 5429 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5430 "Invalid FP_ROUND!"); 5431 if (N1.getValueType() == VT) return N1; // noop conversion. 5432 break; 5433 case ISD::AssertSext: 5434 case ISD::AssertZext: { 5435 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5436 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5437 assert(VT.isInteger() && EVT.isInteger() && 5438 "Cannot *_EXTEND_INREG FP types"); 5439 assert(!EVT.isVector() && 5440 "AssertSExt/AssertZExt type should be the vector element type " 5441 "rather than the vector type!"); 5442 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5443 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5444 break; 5445 } 5446 case ISD::SIGN_EXTEND_INREG: { 5447 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5448 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5449 assert(VT.isInteger() && EVT.isInteger() && 5450 "Cannot *_EXTEND_INREG FP types"); 5451 assert(EVT.isVector() == VT.isVector() && 5452 "SIGN_EXTEND_INREG type should be vector iff the operand " 5453 "type is vector!"); 5454 assert((!EVT.isVector() || 5455 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5456 "Vector element counts must match in SIGN_EXTEND_INREG"); 5457 assert(EVT.bitsLE(VT) && "Not extending!"); 5458 if (EVT == VT) return N1; // Not actually extending 5459 5460 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5461 unsigned FromBits = EVT.getScalarSizeInBits(); 5462 Val <<= Val.getBitWidth() - FromBits; 5463 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5464 return getConstant(Val, DL, ConstantVT); 5465 }; 5466 5467 if (N1C) { 5468 const APInt &Val = N1C->getAPIntValue(); 5469 return SignExtendInReg(Val, VT); 5470 } 5471 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5472 SmallVector<SDValue, 8> Ops; 5473 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5474 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5475 SDValue Op = N1.getOperand(i); 5476 if (Op.isUndef()) { 5477 Ops.push_back(getUNDEF(OpVT)); 5478 continue; 5479 } 5480 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5481 APInt Val = C->getAPIntValue(); 5482 Ops.push_back(SignExtendInReg(Val, OpVT)); 5483 } 5484 return getBuildVector(VT, DL, Ops); 5485 } 5486 break; 5487 } 5488 case ISD::EXTRACT_VECTOR_ELT: 5489 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5490 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5491 element type of the vector."); 5492 5493 // Extract from an undefined value or using an undefined index is undefined. 5494 if (N1.isUndef() || N2.isUndef()) 5495 return getUNDEF(VT); 5496 5497 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5498 // vectors. For scalable vectors we will provide appropriate support for 5499 // dealing with arbitrary indices. 5500 if (N2C && N1.getValueType().isFixedLengthVector() && 5501 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5502 return getUNDEF(VT); 5503 5504 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5505 // expanding copies of large vectors from registers. This only works for 5506 // fixed length vectors, since we need to know the exact number of 5507 // elements. 5508 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5509 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5510 unsigned Factor = 5511 N1.getOperand(0).getValueType().getVectorNumElements(); 5512 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5513 N1.getOperand(N2C->getZExtValue() / Factor), 5514 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5515 } 5516 5517 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5518 // lowering is expanding large vector constants. 5519 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5520 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5521 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5522 N1.getValueType().isFixedLengthVector()) && 5523 "BUILD_VECTOR used for scalable vectors"); 5524 unsigned Index = 5525 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5526 SDValue Elt = N1.getOperand(Index); 5527 5528 if (VT != Elt.getValueType()) 5529 // If the vector element type is not legal, the BUILD_VECTOR operands 5530 // are promoted and implicitly truncated, and the result implicitly 5531 // extended. Make that explicit here. 5532 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5533 5534 return Elt; 5535 } 5536 5537 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5538 // operations are lowered to scalars. 5539 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5540 // If the indices are the same, return the inserted element else 5541 // if the indices are known different, extract the element from 5542 // the original vector. 5543 SDValue N1Op2 = N1.getOperand(2); 5544 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5545 5546 if (N1Op2C && N2C) { 5547 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5548 if (VT == N1.getOperand(1).getValueType()) 5549 return N1.getOperand(1); 5550 else 5551 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5552 } 5553 5554 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5555 } 5556 } 5557 5558 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5559 // when vector types are scalarized and v1iX is legal. 5560 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5561 // Here we are completely ignoring the extract element index (N2), 5562 // which is fine for fixed width vectors, since any index other than 0 5563 // is undefined anyway. However, this cannot be ignored for scalable 5564 // vectors - in theory we could support this, but we don't want to do this 5565 // without a profitability check. 5566 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5567 N1.getValueType().isFixedLengthVector() && 5568 N1.getValueType().getVectorNumElements() == 1) { 5569 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5570 N1.getOperand(1)); 5571 } 5572 break; 5573 case ISD::EXTRACT_ELEMENT: 5574 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5575 assert(!N1.getValueType().isVector() && !VT.isVector() && 5576 (N1.getValueType().isInteger() == VT.isInteger()) && 5577 N1.getValueType() != VT && 5578 "Wrong types for EXTRACT_ELEMENT!"); 5579 5580 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5581 // 64-bit integers into 32-bit parts. Instead of building the extract of 5582 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5583 if (N1.getOpcode() == ISD::BUILD_PAIR) 5584 return N1.getOperand(N2C->getZExtValue()); 5585 5586 // EXTRACT_ELEMENT of a constant int is also very common. 5587 if (N1C) { 5588 unsigned ElementSize = VT.getSizeInBits(); 5589 unsigned Shift = ElementSize * N2C->getZExtValue(); 5590 const APInt &Val = N1C->getAPIntValue(); 5591 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5592 } 5593 break; 5594 case ISD::EXTRACT_SUBVECTOR: 5595 EVT N1VT = N1.getValueType(); 5596 assert(VT.isVector() && N1VT.isVector() && 5597 "Extract subvector VTs must be vectors!"); 5598 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5599 "Extract subvector VTs must have the same element type!"); 5600 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5601 "Cannot extract a scalable vector from a fixed length vector!"); 5602 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5603 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5604 "Extract subvector must be from larger vector to smaller vector!"); 5605 assert(N2C && "Extract subvector index must be a constant"); 5606 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5607 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5608 N1VT.getVectorMinNumElements()) && 5609 "Extract subvector overflow!"); 5610 assert(N2C->getAPIntValue().getBitWidth() == 5611 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5612 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5613 5614 // Trivial extraction. 5615 if (VT == N1VT) 5616 return N1; 5617 5618 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5619 if (N1.isUndef()) 5620 return getUNDEF(VT); 5621 5622 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5623 // the concat have the same type as the extract. 5624 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5625 VT == N1.getOperand(0).getValueType()) { 5626 unsigned Factor = VT.getVectorMinNumElements(); 5627 return N1.getOperand(N2C->getZExtValue() / Factor); 5628 } 5629 5630 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5631 // during shuffle legalization. 5632 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5633 VT == N1.getOperand(1).getValueType()) 5634 return N1.getOperand(1); 5635 break; 5636 } 5637 5638 // Perform trivial constant folding. 5639 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5640 return SV; 5641 5642 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5643 return V; 5644 5645 // Canonicalize an UNDEF to the RHS, even over a constant. 5646 if (N1.isUndef()) { 5647 if (TLI->isCommutativeBinOp(Opcode)) { 5648 std::swap(N1, N2); 5649 } else { 5650 switch (Opcode) { 5651 case ISD::SIGN_EXTEND_INREG: 5652 case ISD::SUB: 5653 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5654 case ISD::UDIV: 5655 case ISD::SDIV: 5656 case ISD::UREM: 5657 case ISD::SREM: 5658 case ISD::SSUBSAT: 5659 case ISD::USUBSAT: 5660 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5661 } 5662 } 5663 } 5664 5665 // Fold a bunch of operators when the RHS is undef. 5666 if (N2.isUndef()) { 5667 switch (Opcode) { 5668 case ISD::XOR: 5669 if (N1.isUndef()) 5670 // Handle undef ^ undef -> 0 special case. This is a common 5671 // idiom (misuse). 5672 return getConstant(0, DL, VT); 5673 LLVM_FALLTHROUGH; 5674 case ISD::ADD: 5675 case ISD::SUB: 5676 case ISD::UDIV: 5677 case ISD::SDIV: 5678 case ISD::UREM: 5679 case ISD::SREM: 5680 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5681 case ISD::MUL: 5682 case ISD::AND: 5683 case ISD::SSUBSAT: 5684 case ISD::USUBSAT: 5685 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5686 case ISD::OR: 5687 case ISD::SADDSAT: 5688 case ISD::UADDSAT: 5689 return getAllOnesConstant(DL, VT); 5690 } 5691 } 5692 5693 // Memoize this node if possible. 5694 SDNode *N; 5695 SDVTList VTs = getVTList(VT); 5696 SDValue Ops[] = {N1, N2}; 5697 if (VT != MVT::Glue) { 5698 FoldingSetNodeID ID; 5699 AddNodeIDNode(ID, Opcode, VTs, Ops); 5700 void *IP = nullptr; 5701 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5702 E->intersectFlagsWith(Flags); 5703 return SDValue(E, 0); 5704 } 5705 5706 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5707 N->setFlags(Flags); 5708 createOperands(N, Ops); 5709 CSEMap.InsertNode(N, IP); 5710 } else { 5711 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5712 createOperands(N, Ops); 5713 } 5714 5715 InsertNode(N); 5716 SDValue V = SDValue(N, 0); 5717 NewSDValueDbgMsg(V, "Creating new node: ", this); 5718 return V; 5719 } 5720 5721 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5722 SDValue N1, SDValue N2, SDValue N3) { 5723 SDNodeFlags Flags; 5724 if (Inserter) 5725 Flags = Inserter->getFlags(); 5726 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5727 } 5728 5729 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5730 SDValue N1, SDValue N2, SDValue N3, 5731 const SDNodeFlags Flags) { 5732 // Perform various simplifications. 5733 switch (Opcode) { 5734 case ISD::FMA: { 5735 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5736 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5737 N3.getValueType() == VT && "FMA types must match!"); 5738 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5739 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5740 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5741 if (N1CFP && N2CFP && N3CFP) { 5742 APFloat V1 = N1CFP->getValueAPF(); 5743 const APFloat &V2 = N2CFP->getValueAPF(); 5744 const APFloat &V3 = N3CFP->getValueAPF(); 5745 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5746 return getConstantFP(V1, DL, VT); 5747 } 5748 break; 5749 } 5750 case ISD::BUILD_VECTOR: { 5751 // Attempt to simplify BUILD_VECTOR. 5752 SDValue Ops[] = {N1, N2, N3}; 5753 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5754 return V; 5755 break; 5756 } 5757 case ISD::CONCAT_VECTORS: { 5758 SDValue Ops[] = {N1, N2, N3}; 5759 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5760 return V; 5761 break; 5762 } 5763 case ISD::SETCC: { 5764 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5765 assert(N1.getValueType() == N2.getValueType() && 5766 "SETCC operands must have the same type!"); 5767 assert(VT.isVector() == N1.getValueType().isVector() && 5768 "SETCC type should be vector iff the operand type is vector!"); 5769 assert((!VT.isVector() || VT.getVectorElementCount() == 5770 N1.getValueType().getVectorElementCount()) && 5771 "SETCC vector element counts must match!"); 5772 // Use FoldSetCC to simplify SETCC's. 5773 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5774 return V; 5775 // Vector constant folding. 5776 SDValue Ops[] = {N1, N2, N3}; 5777 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5778 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5779 return V; 5780 } 5781 break; 5782 } 5783 case ISD::SELECT: 5784 case ISD::VSELECT: 5785 if (SDValue V = simplifySelect(N1, N2, N3)) 5786 return V; 5787 break; 5788 case ISD::VECTOR_SHUFFLE: 5789 llvm_unreachable("should use getVectorShuffle constructor!"); 5790 case ISD::INSERT_VECTOR_ELT: { 5791 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5792 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 5793 // for scalable vectors where we will generate appropriate code to 5794 // deal with out-of-bounds cases correctly. 5795 if (N3C && N1.getValueType().isFixedLengthVector() && 5796 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5797 return getUNDEF(VT); 5798 5799 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 5800 if (N3.isUndef()) 5801 return getUNDEF(VT); 5802 5803 // If the inserted element is an UNDEF, just use the input vector. 5804 if (N2.isUndef()) 5805 return N1; 5806 5807 break; 5808 } 5809 case ISD::INSERT_SUBVECTOR: { 5810 // Inserting undef into undef is still undef. 5811 if (N1.isUndef() && N2.isUndef()) 5812 return getUNDEF(VT); 5813 5814 EVT N2VT = N2.getValueType(); 5815 assert(VT == N1.getValueType() && 5816 "Dest and insert subvector source types must match!"); 5817 assert(VT.isVector() && N2VT.isVector() && 5818 "Insert subvector VTs must be vectors!"); 5819 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 5820 "Cannot insert a scalable vector into a fixed length vector!"); 5821 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5822 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 5823 "Insert subvector must be from smaller vector to larger vector!"); 5824 assert(isa<ConstantSDNode>(N3) && 5825 "Insert subvector index must be constant"); 5826 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5827 (N2VT.getVectorMinNumElements() + 5828 cast<ConstantSDNode>(N3)->getZExtValue()) <= 5829 VT.getVectorMinNumElements()) && 5830 "Insert subvector overflow!"); 5831 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 5832 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5833 "Constant index for INSERT_SUBVECTOR has an invalid size"); 5834 5835 // Trivial insertion. 5836 if (VT == N2VT) 5837 return N2; 5838 5839 // If this is an insert of an extracted vector into an undef vector, we 5840 // can just use the input to the extract. 5841 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5842 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 5843 return N2.getOperand(0); 5844 break; 5845 } 5846 case ISD::BITCAST: 5847 // Fold bit_convert nodes from a type to themselves. 5848 if (N1.getValueType() == VT) 5849 return N1; 5850 break; 5851 } 5852 5853 // Memoize node if it doesn't produce a flag. 5854 SDNode *N; 5855 SDVTList VTs = getVTList(VT); 5856 SDValue Ops[] = {N1, N2, N3}; 5857 if (VT != MVT::Glue) { 5858 FoldingSetNodeID ID; 5859 AddNodeIDNode(ID, Opcode, VTs, Ops); 5860 void *IP = nullptr; 5861 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5862 E->intersectFlagsWith(Flags); 5863 return SDValue(E, 0); 5864 } 5865 5866 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5867 N->setFlags(Flags); 5868 createOperands(N, Ops); 5869 CSEMap.InsertNode(N, IP); 5870 } else { 5871 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5872 createOperands(N, Ops); 5873 } 5874 5875 InsertNode(N); 5876 SDValue V = SDValue(N, 0); 5877 NewSDValueDbgMsg(V, "Creating new node: ", this); 5878 return V; 5879 } 5880 5881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5882 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5883 SDValue Ops[] = { N1, N2, N3, N4 }; 5884 return getNode(Opcode, DL, VT, Ops); 5885 } 5886 5887 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5888 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5889 SDValue N5) { 5890 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5891 return getNode(Opcode, DL, VT, Ops); 5892 } 5893 5894 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 5895 /// the incoming stack arguments to be loaded from the stack. 5896 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 5897 SmallVector<SDValue, 8> ArgChains; 5898 5899 // Include the original chain at the beginning of the list. When this is 5900 // used by target LowerCall hooks, this helps legalize find the 5901 // CALLSEQ_BEGIN node. 5902 ArgChains.push_back(Chain); 5903 5904 // Add a chain value for each stack argument. 5905 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 5906 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 5907 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5908 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5909 if (FI->getIndex() < 0) 5910 ArgChains.push_back(SDValue(L, 1)); 5911 5912 // Build a tokenfactor for all the chains. 5913 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5914 } 5915 5916 /// getMemsetValue - Vectorized representation of the memset value 5917 /// operand. 5918 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 5919 const SDLoc &dl) { 5920 assert(!Value.isUndef()); 5921 5922 unsigned NumBits = VT.getScalarSizeInBits(); 5923 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 5924 assert(C->getAPIntValue().getBitWidth() == 8); 5925 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 5926 if (VT.isInteger()) { 5927 bool IsOpaque = VT.getSizeInBits() > 64 || 5928 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 5929 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 5930 } 5931 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 5932 VT); 5933 } 5934 5935 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 5936 EVT IntVT = VT.getScalarType(); 5937 if (!IntVT.isInteger()) 5938 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 5939 5940 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 5941 if (NumBits > 8) { 5942 // Use a multiplication with 0x010101... to extend the input to the 5943 // required length. 5944 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 5945 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 5946 DAG.getConstant(Magic, dl, IntVT)); 5947 } 5948 5949 if (VT != Value.getValueType() && !VT.isInteger()) 5950 Value = DAG.getBitcast(VT.getScalarType(), Value); 5951 if (VT != Value.getValueType()) 5952 Value = DAG.getSplatBuildVector(VT, dl, Value); 5953 5954 return Value; 5955 } 5956 5957 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 5958 /// used when a memcpy is turned into a memset when the source is a constant 5959 /// string ptr. 5960 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 5961 const TargetLowering &TLI, 5962 const ConstantDataArraySlice &Slice) { 5963 // Handle vector with all elements zero. 5964 if (Slice.Array == nullptr) { 5965 if (VT.isInteger()) 5966 return DAG.getConstant(0, dl, VT); 5967 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 5968 return DAG.getConstantFP(0.0, dl, VT); 5969 else if (VT.isVector()) { 5970 unsigned NumElts = VT.getVectorNumElements(); 5971 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 5972 return DAG.getNode(ISD::BITCAST, dl, VT, 5973 DAG.getConstant(0, dl, 5974 EVT::getVectorVT(*DAG.getContext(), 5975 EltVT, NumElts))); 5976 } else 5977 llvm_unreachable("Expected type!"); 5978 } 5979 5980 assert(!VT.isVector() && "Can't handle vector type here!"); 5981 unsigned NumVTBits = VT.getSizeInBits(); 5982 unsigned NumVTBytes = NumVTBits / 8; 5983 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 5984 5985 APInt Val(NumVTBits, 0); 5986 if (DAG.getDataLayout().isLittleEndian()) { 5987 for (unsigned i = 0; i != NumBytes; ++i) 5988 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 5989 } else { 5990 for (unsigned i = 0; i != NumBytes; ++i) 5991 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 5992 } 5993 5994 // If the "cost" of materializing the integer immediate is less than the cost 5995 // of a load, then it is cost effective to turn the load into the immediate. 5996 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 5997 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 5998 return DAG.getConstant(Val, dl, VT); 5999 return SDValue(nullptr, 0); 6000 } 6001 6002 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6003 const SDLoc &DL, 6004 const SDNodeFlags Flags) { 6005 EVT VT = Base.getValueType(); 6006 SDValue Index; 6007 6008 if (Offset.isScalable()) 6009 Index = getVScale(DL, Base.getValueType(), 6010 APInt(Base.getValueSizeInBits().getFixedSize(), 6011 Offset.getKnownMinSize())); 6012 else 6013 Index = getConstant(Offset.getFixedSize(), DL, VT); 6014 6015 return getMemBasePlusOffset(Base, Index, DL, Flags); 6016 } 6017 6018 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6019 const SDLoc &DL, 6020 const SDNodeFlags Flags) { 6021 assert(Offset.getValueType().isInteger()); 6022 EVT BasePtrVT = Ptr.getValueType(); 6023 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6024 } 6025 6026 /// Returns true if memcpy source is constant data. 6027 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6028 uint64_t SrcDelta = 0; 6029 GlobalAddressSDNode *G = nullptr; 6030 if (Src.getOpcode() == ISD::GlobalAddress) 6031 G = cast<GlobalAddressSDNode>(Src); 6032 else if (Src.getOpcode() == ISD::ADD && 6033 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6034 Src.getOperand(1).getOpcode() == ISD::Constant) { 6035 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6036 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6037 } 6038 if (!G) 6039 return false; 6040 6041 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6042 SrcDelta + G->getOffset()); 6043 } 6044 6045 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6046 SelectionDAG &DAG) { 6047 // On Darwin, -Os means optimize for size without hurting performance, so 6048 // only really optimize for size when -Oz (MinSize) is used. 6049 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6050 return MF.getFunction().hasMinSize(); 6051 return DAG.shouldOptForSize(); 6052 } 6053 6054 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6055 SmallVector<SDValue, 32> &OutChains, unsigned From, 6056 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6057 SmallVector<SDValue, 16> &OutStoreChains) { 6058 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6059 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6060 SmallVector<SDValue, 16> GluedLoadChains; 6061 for (unsigned i = From; i < To; ++i) { 6062 OutChains.push_back(OutLoadChains[i]); 6063 GluedLoadChains.push_back(OutLoadChains[i]); 6064 } 6065 6066 // Chain for all loads. 6067 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6068 GluedLoadChains); 6069 6070 for (unsigned i = From; i < To; ++i) { 6071 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6072 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6073 ST->getBasePtr(), ST->getMemoryVT(), 6074 ST->getMemOperand()); 6075 OutChains.push_back(NewStore); 6076 } 6077 } 6078 6079 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6080 SDValue Chain, SDValue Dst, SDValue Src, 6081 uint64_t Size, Align Alignment, 6082 bool isVol, bool AlwaysInline, 6083 MachinePointerInfo DstPtrInfo, 6084 MachinePointerInfo SrcPtrInfo) { 6085 // Turn a memcpy of undef to nop. 6086 // FIXME: We need to honor volatile even is Src is undef. 6087 if (Src.isUndef()) 6088 return Chain; 6089 6090 // Expand memcpy to a series of load and store ops if the size operand falls 6091 // below a certain threshold. 6092 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6093 // rather than maybe a humongous number of loads and stores. 6094 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6095 const DataLayout &DL = DAG.getDataLayout(); 6096 LLVMContext &C = *DAG.getContext(); 6097 std::vector<EVT> MemOps; 6098 bool DstAlignCanChange = false; 6099 MachineFunction &MF = DAG.getMachineFunction(); 6100 MachineFrameInfo &MFI = MF.getFrameInfo(); 6101 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6102 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6103 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6104 DstAlignCanChange = true; 6105 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6106 if (!SrcAlign || Alignment > *SrcAlign) 6107 SrcAlign = Alignment; 6108 assert(SrcAlign && "SrcAlign must be set"); 6109 ConstantDataArraySlice Slice; 6110 // If marked as volatile, perform a copy even when marked as constant. 6111 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6112 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6113 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6114 const MemOp Op = isZeroConstant 6115 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6116 /*IsZeroMemset*/ true, isVol) 6117 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6118 *SrcAlign, isVol, CopyFromConstant); 6119 if (!TLI.findOptimalMemOpLowering( 6120 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6121 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6122 return SDValue(); 6123 6124 if (DstAlignCanChange) { 6125 Type *Ty = MemOps[0].getTypeForEVT(C); 6126 Align NewAlign = DL.getABITypeAlign(Ty); 6127 6128 // Don't promote to an alignment that would require dynamic stack 6129 // realignment. 6130 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6131 if (!TRI->needsStackRealignment(MF)) 6132 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6133 NewAlign = NewAlign / 2; 6134 6135 if (NewAlign > Alignment) { 6136 // Give the stack frame object a larger alignment if needed. 6137 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6138 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6139 Alignment = NewAlign; 6140 } 6141 } 6142 6143 MachineMemOperand::Flags MMOFlags = 6144 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6145 SmallVector<SDValue, 16> OutLoadChains; 6146 SmallVector<SDValue, 16> OutStoreChains; 6147 SmallVector<SDValue, 32> OutChains; 6148 unsigned NumMemOps = MemOps.size(); 6149 uint64_t SrcOff = 0, DstOff = 0; 6150 for (unsigned i = 0; i != NumMemOps; ++i) { 6151 EVT VT = MemOps[i]; 6152 unsigned VTSize = VT.getSizeInBits() / 8; 6153 SDValue Value, Store; 6154 6155 if (VTSize > Size) { 6156 // Issuing an unaligned load / store pair that overlaps with the previous 6157 // pair. Adjust the offset accordingly. 6158 assert(i == NumMemOps-1 && i != 0); 6159 SrcOff -= VTSize - Size; 6160 DstOff -= VTSize - Size; 6161 } 6162 6163 if (CopyFromConstant && 6164 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6165 // It's unlikely a store of a vector immediate can be done in a single 6166 // instruction. It would require a load from a constantpool first. 6167 // We only handle zero vectors here. 6168 // FIXME: Handle other cases where store of vector immediate is done in 6169 // a single instruction. 6170 ConstantDataArraySlice SubSlice; 6171 if (SrcOff < Slice.Length) { 6172 SubSlice = Slice; 6173 SubSlice.move(SrcOff); 6174 } else { 6175 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6176 SubSlice.Array = nullptr; 6177 SubSlice.Offset = 0; 6178 SubSlice.Length = VTSize; 6179 } 6180 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6181 if (Value.getNode()) { 6182 Store = DAG.getStore( 6183 Chain, dl, Value, 6184 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6185 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6186 OutChains.push_back(Store); 6187 } 6188 } 6189 6190 if (!Store.getNode()) { 6191 // The type might not be legal for the target. This should only happen 6192 // if the type is smaller than a legal type, as on PPC, so the right 6193 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6194 // to Load/Store if NVT==VT. 6195 // FIXME does the case above also need this? 6196 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6197 assert(NVT.bitsGE(VT)); 6198 6199 bool isDereferenceable = 6200 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6201 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6202 if (isDereferenceable) 6203 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6204 6205 Value = DAG.getExtLoad( 6206 ISD::EXTLOAD, dl, NVT, Chain, 6207 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6208 SrcPtrInfo.getWithOffset(SrcOff), VT, 6209 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6210 OutLoadChains.push_back(Value.getValue(1)); 6211 6212 Store = DAG.getTruncStore( 6213 Chain, dl, Value, 6214 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6215 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6216 OutStoreChains.push_back(Store); 6217 } 6218 SrcOff += VTSize; 6219 DstOff += VTSize; 6220 Size -= VTSize; 6221 } 6222 6223 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6224 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6225 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6226 6227 if (NumLdStInMemcpy) { 6228 // It may be that memcpy might be converted to memset if it's memcpy 6229 // of constants. In such a case, we won't have loads and stores, but 6230 // just stores. In the absence of loads, there is nothing to gang up. 6231 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6232 // If target does not care, just leave as it. 6233 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6234 OutChains.push_back(OutLoadChains[i]); 6235 OutChains.push_back(OutStoreChains[i]); 6236 } 6237 } else { 6238 // Ld/St less than/equal limit set by target. 6239 if (NumLdStInMemcpy <= GluedLdStLimit) { 6240 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6241 NumLdStInMemcpy, OutLoadChains, 6242 OutStoreChains); 6243 } else { 6244 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6245 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6246 unsigned GlueIter = 0; 6247 6248 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6249 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6250 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6251 6252 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6253 OutLoadChains, OutStoreChains); 6254 GlueIter += GluedLdStLimit; 6255 } 6256 6257 // Residual ld/st. 6258 if (RemainingLdStInMemcpy) { 6259 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6260 RemainingLdStInMemcpy, OutLoadChains, 6261 OutStoreChains); 6262 } 6263 } 6264 } 6265 } 6266 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6267 } 6268 6269 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6270 SDValue Chain, SDValue Dst, SDValue Src, 6271 uint64_t Size, Align Alignment, 6272 bool isVol, bool AlwaysInline, 6273 MachinePointerInfo DstPtrInfo, 6274 MachinePointerInfo SrcPtrInfo) { 6275 // Turn a memmove of undef to nop. 6276 // FIXME: We need to honor volatile even is Src is undef. 6277 if (Src.isUndef()) 6278 return Chain; 6279 6280 // Expand memmove to a series of load and store ops if the size operand falls 6281 // below a certain threshold. 6282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6283 const DataLayout &DL = DAG.getDataLayout(); 6284 LLVMContext &C = *DAG.getContext(); 6285 std::vector<EVT> MemOps; 6286 bool DstAlignCanChange = false; 6287 MachineFunction &MF = DAG.getMachineFunction(); 6288 MachineFrameInfo &MFI = MF.getFrameInfo(); 6289 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6290 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6291 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6292 DstAlignCanChange = true; 6293 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6294 if (!SrcAlign || Alignment > *SrcAlign) 6295 SrcAlign = Alignment; 6296 assert(SrcAlign && "SrcAlign must be set"); 6297 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6298 if (!TLI.findOptimalMemOpLowering( 6299 MemOps, Limit, 6300 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6301 /*IsVolatile*/ true), 6302 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6303 MF.getFunction().getAttributes())) 6304 return SDValue(); 6305 6306 if (DstAlignCanChange) { 6307 Type *Ty = MemOps[0].getTypeForEVT(C); 6308 Align NewAlign = DL.getABITypeAlign(Ty); 6309 if (NewAlign > Alignment) { 6310 // Give the stack frame object a larger alignment if needed. 6311 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6312 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6313 Alignment = NewAlign; 6314 } 6315 } 6316 6317 MachineMemOperand::Flags MMOFlags = 6318 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6319 uint64_t SrcOff = 0, DstOff = 0; 6320 SmallVector<SDValue, 8> LoadValues; 6321 SmallVector<SDValue, 8> LoadChains; 6322 SmallVector<SDValue, 8> OutChains; 6323 unsigned NumMemOps = MemOps.size(); 6324 for (unsigned i = 0; i < NumMemOps; i++) { 6325 EVT VT = MemOps[i]; 6326 unsigned VTSize = VT.getSizeInBits() / 8; 6327 SDValue Value; 6328 6329 bool isDereferenceable = 6330 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6331 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6332 if (isDereferenceable) 6333 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6334 6335 Value = 6336 DAG.getLoad(VT, dl, Chain, 6337 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6338 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6339 LoadValues.push_back(Value); 6340 LoadChains.push_back(Value.getValue(1)); 6341 SrcOff += VTSize; 6342 } 6343 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6344 OutChains.clear(); 6345 for (unsigned i = 0; i < NumMemOps; i++) { 6346 EVT VT = MemOps[i]; 6347 unsigned VTSize = VT.getSizeInBits() / 8; 6348 SDValue Store; 6349 6350 Store = 6351 DAG.getStore(Chain, dl, LoadValues[i], 6352 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6353 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6354 OutChains.push_back(Store); 6355 DstOff += VTSize; 6356 } 6357 6358 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6359 } 6360 6361 /// Lower the call to 'memset' intrinsic function into a series of store 6362 /// operations. 6363 /// 6364 /// \param DAG Selection DAG where lowered code is placed. 6365 /// \param dl Link to corresponding IR location. 6366 /// \param Chain Control flow dependency. 6367 /// \param Dst Pointer to destination memory location. 6368 /// \param Src Value of byte to write into the memory. 6369 /// \param Size Number of bytes to write. 6370 /// \param Alignment Alignment of the destination in bytes. 6371 /// \param isVol True if destination is volatile. 6372 /// \param DstPtrInfo IR information on the memory pointer. 6373 /// \returns New head in the control flow, if lowering was successful, empty 6374 /// SDValue otherwise. 6375 /// 6376 /// The function tries to replace 'llvm.memset' intrinsic with several store 6377 /// operations and value calculation code. This is usually profitable for small 6378 /// memory size. 6379 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6380 SDValue Chain, SDValue Dst, SDValue Src, 6381 uint64_t Size, Align Alignment, bool isVol, 6382 MachinePointerInfo DstPtrInfo) { 6383 // Turn a memset of undef to nop. 6384 // FIXME: We need to honor volatile even is Src is undef. 6385 if (Src.isUndef()) 6386 return Chain; 6387 6388 // Expand memset to a series of load/store ops if the size operand 6389 // falls below a certain threshold. 6390 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6391 std::vector<EVT> MemOps; 6392 bool DstAlignCanChange = false; 6393 MachineFunction &MF = DAG.getMachineFunction(); 6394 MachineFrameInfo &MFI = MF.getFrameInfo(); 6395 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6396 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6397 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6398 DstAlignCanChange = true; 6399 bool IsZeroVal = 6400 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6401 if (!TLI.findOptimalMemOpLowering( 6402 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6403 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6404 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6405 return SDValue(); 6406 6407 if (DstAlignCanChange) { 6408 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6409 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6410 if (NewAlign > Alignment) { 6411 // Give the stack frame object a larger alignment if needed. 6412 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6413 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6414 Alignment = NewAlign; 6415 } 6416 } 6417 6418 SmallVector<SDValue, 8> OutChains; 6419 uint64_t DstOff = 0; 6420 unsigned NumMemOps = MemOps.size(); 6421 6422 // Find the largest store and generate the bit pattern for it. 6423 EVT LargestVT = MemOps[0]; 6424 for (unsigned i = 1; i < NumMemOps; i++) 6425 if (MemOps[i].bitsGT(LargestVT)) 6426 LargestVT = MemOps[i]; 6427 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6428 6429 for (unsigned i = 0; i < NumMemOps; i++) { 6430 EVT VT = MemOps[i]; 6431 unsigned VTSize = VT.getSizeInBits() / 8; 6432 if (VTSize > Size) { 6433 // Issuing an unaligned load / store pair that overlaps with the previous 6434 // pair. Adjust the offset accordingly. 6435 assert(i == NumMemOps-1 && i != 0); 6436 DstOff -= VTSize - Size; 6437 } 6438 6439 // If this store is smaller than the largest store see whether we can get 6440 // the smaller value for free with a truncate. 6441 SDValue Value = MemSetValue; 6442 if (VT.bitsLT(LargestVT)) { 6443 if (!LargestVT.isVector() && !VT.isVector() && 6444 TLI.isTruncateFree(LargestVT, VT)) 6445 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6446 else 6447 Value = getMemsetValue(Src, VT, DAG, dl); 6448 } 6449 assert(Value.getValueType() == VT && "Value with wrong type."); 6450 SDValue Store = DAG.getStore( 6451 Chain, dl, Value, 6452 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6453 DstPtrInfo.getWithOffset(DstOff), Alignment, 6454 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6455 OutChains.push_back(Store); 6456 DstOff += VT.getSizeInBits() / 8; 6457 Size -= VTSize; 6458 } 6459 6460 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6461 } 6462 6463 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6464 unsigned AS) { 6465 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6466 // pointer operands can be losslessly bitcasted to pointers of address space 0 6467 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6468 report_fatal_error("cannot lower memory intrinsic in address space " + 6469 Twine(AS)); 6470 } 6471 } 6472 6473 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6474 SDValue Src, SDValue Size, Align Alignment, 6475 bool isVol, bool AlwaysInline, bool isTailCall, 6476 MachinePointerInfo DstPtrInfo, 6477 MachinePointerInfo SrcPtrInfo) { 6478 // Check to see if we should lower the memcpy to loads and stores first. 6479 // For cases within the target-specified limits, this is the best choice. 6480 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6481 if (ConstantSize) { 6482 // Memcpy with size zero? Just return the original chain. 6483 if (ConstantSize->isNullValue()) 6484 return Chain; 6485 6486 SDValue Result = getMemcpyLoadsAndStores( 6487 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6488 isVol, false, DstPtrInfo, SrcPtrInfo); 6489 if (Result.getNode()) 6490 return Result; 6491 } 6492 6493 // Then check to see if we should lower the memcpy with target-specific 6494 // code. If the target chooses to do this, this is the next best. 6495 if (TSI) { 6496 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6497 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6498 DstPtrInfo, SrcPtrInfo); 6499 if (Result.getNode()) 6500 return Result; 6501 } 6502 6503 // If we really need inline code and the target declined to provide it, 6504 // use a (potentially long) sequence of loads and stores. 6505 if (AlwaysInline) { 6506 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6507 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6508 ConstantSize->getZExtValue(), Alignment, 6509 isVol, true, DstPtrInfo, SrcPtrInfo); 6510 } 6511 6512 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6513 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6514 6515 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6516 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6517 // respect volatile, so they may do things like read or write memory 6518 // beyond the given memory regions. But fixing this isn't easy, and most 6519 // people don't care. 6520 6521 // Emit a library call. 6522 TargetLowering::ArgListTy Args; 6523 TargetLowering::ArgListEntry Entry; 6524 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6525 Entry.Node = Dst; Args.push_back(Entry); 6526 Entry.Node = Src; Args.push_back(Entry); 6527 6528 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6529 Entry.Node = Size; Args.push_back(Entry); 6530 // FIXME: pass in SDLoc 6531 TargetLowering::CallLoweringInfo CLI(*this); 6532 CLI.setDebugLoc(dl) 6533 .setChain(Chain) 6534 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6535 Dst.getValueType().getTypeForEVT(*getContext()), 6536 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6537 TLI->getPointerTy(getDataLayout())), 6538 std::move(Args)) 6539 .setDiscardResult() 6540 .setTailCall(isTailCall); 6541 6542 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6543 return CallResult.second; 6544 } 6545 6546 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6547 SDValue Dst, unsigned DstAlign, 6548 SDValue Src, unsigned SrcAlign, 6549 SDValue Size, Type *SizeTy, 6550 unsigned ElemSz, bool isTailCall, 6551 MachinePointerInfo DstPtrInfo, 6552 MachinePointerInfo SrcPtrInfo) { 6553 // Emit a library call. 6554 TargetLowering::ArgListTy Args; 6555 TargetLowering::ArgListEntry Entry; 6556 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6557 Entry.Node = Dst; 6558 Args.push_back(Entry); 6559 6560 Entry.Node = Src; 6561 Args.push_back(Entry); 6562 6563 Entry.Ty = SizeTy; 6564 Entry.Node = Size; 6565 Args.push_back(Entry); 6566 6567 RTLIB::Libcall LibraryCall = 6568 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6569 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6570 report_fatal_error("Unsupported element size"); 6571 6572 TargetLowering::CallLoweringInfo CLI(*this); 6573 CLI.setDebugLoc(dl) 6574 .setChain(Chain) 6575 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6576 Type::getVoidTy(*getContext()), 6577 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6578 TLI->getPointerTy(getDataLayout())), 6579 std::move(Args)) 6580 .setDiscardResult() 6581 .setTailCall(isTailCall); 6582 6583 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6584 return CallResult.second; 6585 } 6586 6587 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6588 SDValue Src, SDValue Size, Align Alignment, 6589 bool isVol, bool isTailCall, 6590 MachinePointerInfo DstPtrInfo, 6591 MachinePointerInfo SrcPtrInfo) { 6592 // Check to see if we should lower the memmove to loads and stores first. 6593 // For cases within the target-specified limits, this is the best choice. 6594 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6595 if (ConstantSize) { 6596 // Memmove with size zero? Just return the original chain. 6597 if (ConstantSize->isNullValue()) 6598 return Chain; 6599 6600 SDValue Result = getMemmoveLoadsAndStores( 6601 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6602 isVol, false, DstPtrInfo, SrcPtrInfo); 6603 if (Result.getNode()) 6604 return Result; 6605 } 6606 6607 // Then check to see if we should lower the memmove with target-specific 6608 // code. If the target chooses to do this, this is the next best. 6609 if (TSI) { 6610 SDValue Result = 6611 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6612 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6613 if (Result.getNode()) 6614 return Result; 6615 } 6616 6617 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6618 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6619 6620 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6621 // not be safe. See memcpy above for more details. 6622 6623 // Emit a library call. 6624 TargetLowering::ArgListTy Args; 6625 TargetLowering::ArgListEntry Entry; 6626 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6627 Entry.Node = Dst; Args.push_back(Entry); 6628 Entry.Node = Src; Args.push_back(Entry); 6629 6630 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6631 Entry.Node = Size; Args.push_back(Entry); 6632 // FIXME: pass in SDLoc 6633 TargetLowering::CallLoweringInfo CLI(*this); 6634 CLI.setDebugLoc(dl) 6635 .setChain(Chain) 6636 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6637 Dst.getValueType().getTypeForEVT(*getContext()), 6638 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6639 TLI->getPointerTy(getDataLayout())), 6640 std::move(Args)) 6641 .setDiscardResult() 6642 .setTailCall(isTailCall); 6643 6644 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6645 return CallResult.second; 6646 } 6647 6648 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6649 SDValue Dst, unsigned DstAlign, 6650 SDValue Src, unsigned SrcAlign, 6651 SDValue Size, Type *SizeTy, 6652 unsigned ElemSz, bool isTailCall, 6653 MachinePointerInfo DstPtrInfo, 6654 MachinePointerInfo SrcPtrInfo) { 6655 // Emit a library call. 6656 TargetLowering::ArgListTy Args; 6657 TargetLowering::ArgListEntry Entry; 6658 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6659 Entry.Node = Dst; 6660 Args.push_back(Entry); 6661 6662 Entry.Node = Src; 6663 Args.push_back(Entry); 6664 6665 Entry.Ty = SizeTy; 6666 Entry.Node = Size; 6667 Args.push_back(Entry); 6668 6669 RTLIB::Libcall LibraryCall = 6670 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6671 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6672 report_fatal_error("Unsupported element size"); 6673 6674 TargetLowering::CallLoweringInfo CLI(*this); 6675 CLI.setDebugLoc(dl) 6676 .setChain(Chain) 6677 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6678 Type::getVoidTy(*getContext()), 6679 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6680 TLI->getPointerTy(getDataLayout())), 6681 std::move(Args)) 6682 .setDiscardResult() 6683 .setTailCall(isTailCall); 6684 6685 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6686 return CallResult.second; 6687 } 6688 6689 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6690 SDValue Src, SDValue Size, Align Alignment, 6691 bool isVol, bool isTailCall, 6692 MachinePointerInfo DstPtrInfo) { 6693 // Check to see if we should lower the memset to stores first. 6694 // For cases within the target-specified limits, this is the best choice. 6695 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6696 if (ConstantSize) { 6697 // Memset with size zero? Just return the original chain. 6698 if (ConstantSize->isNullValue()) 6699 return Chain; 6700 6701 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6702 ConstantSize->getZExtValue(), Alignment, 6703 isVol, DstPtrInfo); 6704 6705 if (Result.getNode()) 6706 return Result; 6707 } 6708 6709 // Then check to see if we should lower the memset with target-specific 6710 // code. If the target chooses to do this, this is the next best. 6711 if (TSI) { 6712 SDValue Result = TSI->EmitTargetCodeForMemset( 6713 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6714 if (Result.getNode()) 6715 return Result; 6716 } 6717 6718 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6719 6720 // Emit a library call. 6721 TargetLowering::ArgListTy Args; 6722 TargetLowering::ArgListEntry Entry; 6723 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6724 Args.push_back(Entry); 6725 Entry.Node = Src; 6726 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6727 Args.push_back(Entry); 6728 Entry.Node = Size; 6729 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6730 Args.push_back(Entry); 6731 6732 // FIXME: pass in SDLoc 6733 TargetLowering::CallLoweringInfo CLI(*this); 6734 CLI.setDebugLoc(dl) 6735 .setChain(Chain) 6736 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6737 Dst.getValueType().getTypeForEVT(*getContext()), 6738 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6739 TLI->getPointerTy(getDataLayout())), 6740 std::move(Args)) 6741 .setDiscardResult() 6742 .setTailCall(isTailCall); 6743 6744 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6745 return CallResult.second; 6746 } 6747 6748 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6749 SDValue Dst, unsigned DstAlign, 6750 SDValue Value, SDValue Size, Type *SizeTy, 6751 unsigned ElemSz, bool isTailCall, 6752 MachinePointerInfo DstPtrInfo) { 6753 // Emit a library call. 6754 TargetLowering::ArgListTy Args; 6755 TargetLowering::ArgListEntry Entry; 6756 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6757 Entry.Node = Dst; 6758 Args.push_back(Entry); 6759 6760 Entry.Ty = Type::getInt8Ty(*getContext()); 6761 Entry.Node = Value; 6762 Args.push_back(Entry); 6763 6764 Entry.Ty = SizeTy; 6765 Entry.Node = Size; 6766 Args.push_back(Entry); 6767 6768 RTLIB::Libcall LibraryCall = 6769 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6770 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6771 report_fatal_error("Unsupported element size"); 6772 6773 TargetLowering::CallLoweringInfo CLI(*this); 6774 CLI.setDebugLoc(dl) 6775 .setChain(Chain) 6776 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6777 Type::getVoidTy(*getContext()), 6778 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6779 TLI->getPointerTy(getDataLayout())), 6780 std::move(Args)) 6781 .setDiscardResult() 6782 .setTailCall(isTailCall); 6783 6784 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6785 return CallResult.second; 6786 } 6787 6788 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6789 SDVTList VTList, ArrayRef<SDValue> Ops, 6790 MachineMemOperand *MMO) { 6791 FoldingSetNodeID ID; 6792 ID.AddInteger(MemVT.getRawBits()); 6793 AddNodeIDNode(ID, Opcode, VTList, Ops); 6794 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6795 void* IP = nullptr; 6796 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6797 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6798 return SDValue(E, 0); 6799 } 6800 6801 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6802 VTList, MemVT, MMO); 6803 createOperands(N, Ops); 6804 6805 CSEMap.InsertNode(N, IP); 6806 InsertNode(N); 6807 return SDValue(N, 0); 6808 } 6809 6810 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6811 EVT MemVT, SDVTList VTs, SDValue Chain, 6812 SDValue Ptr, SDValue Cmp, SDValue Swp, 6813 MachineMemOperand *MMO) { 6814 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6815 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6816 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6817 6818 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6819 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6820 } 6821 6822 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6823 SDValue Chain, SDValue Ptr, SDValue Val, 6824 MachineMemOperand *MMO) { 6825 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6826 Opcode == ISD::ATOMIC_LOAD_SUB || 6827 Opcode == ISD::ATOMIC_LOAD_AND || 6828 Opcode == ISD::ATOMIC_LOAD_CLR || 6829 Opcode == ISD::ATOMIC_LOAD_OR || 6830 Opcode == ISD::ATOMIC_LOAD_XOR || 6831 Opcode == ISD::ATOMIC_LOAD_NAND || 6832 Opcode == ISD::ATOMIC_LOAD_MIN || 6833 Opcode == ISD::ATOMIC_LOAD_MAX || 6834 Opcode == ISD::ATOMIC_LOAD_UMIN || 6835 Opcode == ISD::ATOMIC_LOAD_UMAX || 6836 Opcode == ISD::ATOMIC_LOAD_FADD || 6837 Opcode == ISD::ATOMIC_LOAD_FSUB || 6838 Opcode == ISD::ATOMIC_SWAP || 6839 Opcode == ISD::ATOMIC_STORE) && 6840 "Invalid Atomic Op"); 6841 6842 EVT VT = Val.getValueType(); 6843 6844 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6845 getVTList(VT, MVT::Other); 6846 SDValue Ops[] = {Chain, Ptr, Val}; 6847 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6848 } 6849 6850 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6851 EVT VT, SDValue Chain, SDValue Ptr, 6852 MachineMemOperand *MMO) { 6853 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6854 6855 SDVTList VTs = getVTList(VT, MVT::Other); 6856 SDValue Ops[] = {Chain, Ptr}; 6857 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6858 } 6859 6860 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6861 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6862 if (Ops.size() == 1) 6863 return Ops[0]; 6864 6865 SmallVector<EVT, 4> VTs; 6866 VTs.reserve(Ops.size()); 6867 for (const SDValue &Op : Ops) 6868 VTs.push_back(Op.getValueType()); 6869 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6870 } 6871 6872 SDValue SelectionDAG::getMemIntrinsicNode( 6873 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6874 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 6875 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 6876 if (!Size && MemVT.isScalableVector()) 6877 Size = MemoryLocation::UnknownSize; 6878 else if (!Size) 6879 Size = MemVT.getStoreSize(); 6880 6881 MachineFunction &MF = getMachineFunction(); 6882 MachineMemOperand *MMO = 6883 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 6884 6885 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 6886 } 6887 6888 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 6889 SDVTList VTList, 6890 ArrayRef<SDValue> Ops, EVT MemVT, 6891 MachineMemOperand *MMO) { 6892 assert((Opcode == ISD::INTRINSIC_VOID || 6893 Opcode == ISD::INTRINSIC_W_CHAIN || 6894 Opcode == ISD::PREFETCH || 6895 ((int)Opcode <= std::numeric_limits<int>::max() && 6896 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 6897 "Opcode is not a memory-accessing opcode!"); 6898 6899 // Memoize the node unless it returns a flag. 6900 MemIntrinsicSDNode *N; 6901 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 6902 FoldingSetNodeID ID; 6903 AddNodeIDNode(ID, Opcode, VTList, Ops); 6904 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 6905 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 6906 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6907 void *IP = nullptr; 6908 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6909 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 6910 return SDValue(E, 0); 6911 } 6912 6913 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6914 VTList, MemVT, MMO); 6915 createOperands(N, Ops); 6916 6917 CSEMap.InsertNode(N, IP); 6918 } else { 6919 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6920 VTList, MemVT, MMO); 6921 createOperands(N, Ops); 6922 } 6923 InsertNode(N); 6924 SDValue V(N, 0); 6925 NewSDValueDbgMsg(V, "Creating new node: ", this); 6926 return V; 6927 } 6928 6929 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 6930 SDValue Chain, int FrameIndex, 6931 int64_t Size, int64_t Offset) { 6932 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 6933 const auto VTs = getVTList(MVT::Other); 6934 SDValue Ops[2] = { 6935 Chain, 6936 getFrameIndex(FrameIndex, 6937 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 6938 true)}; 6939 6940 FoldingSetNodeID ID; 6941 AddNodeIDNode(ID, Opcode, VTs, Ops); 6942 ID.AddInteger(FrameIndex); 6943 ID.AddInteger(Size); 6944 ID.AddInteger(Offset); 6945 void *IP = nullptr; 6946 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 6947 return SDValue(E, 0); 6948 6949 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 6950 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 6951 createOperands(N, Ops); 6952 CSEMap.InsertNode(N, IP); 6953 InsertNode(N); 6954 SDValue V(N, 0); 6955 NewSDValueDbgMsg(V, "Creating new node: ", this); 6956 return V; 6957 } 6958 6959 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 6960 uint64_t Guid, uint64_t Index, 6961 uint32_t Attr) { 6962 const unsigned Opcode = ISD::PSEUDO_PROBE; 6963 const auto VTs = getVTList(MVT::Other); 6964 SDValue Ops[] = {Chain}; 6965 FoldingSetNodeID ID; 6966 AddNodeIDNode(ID, Opcode, VTs, Ops); 6967 ID.AddInteger(Guid); 6968 ID.AddInteger(Index); 6969 void *IP = nullptr; 6970 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 6971 return SDValue(E, 0); 6972 6973 auto *N = newSDNode<PseudoProbeSDNode>( 6974 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 6975 createOperands(N, Ops); 6976 CSEMap.InsertNode(N, IP); 6977 InsertNode(N); 6978 SDValue V(N, 0); 6979 NewSDValueDbgMsg(V, "Creating new node: ", this); 6980 return V; 6981 } 6982 6983 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 6984 /// MachinePointerInfo record from it. This is particularly useful because the 6985 /// code generator has many cases where it doesn't bother passing in a 6986 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 6987 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 6988 SelectionDAG &DAG, SDValue Ptr, 6989 int64_t Offset = 0) { 6990 // If this is FI+Offset, we can model it. 6991 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 6992 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 6993 FI->getIndex(), Offset); 6994 6995 // If this is (FI+Offset1)+Offset2, we can model it. 6996 if (Ptr.getOpcode() != ISD::ADD || 6997 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 6998 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 6999 return Info; 7000 7001 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7002 return MachinePointerInfo::getFixedStack( 7003 DAG.getMachineFunction(), FI, 7004 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7005 } 7006 7007 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7008 /// MachinePointerInfo record from it. This is particularly useful because the 7009 /// code generator has many cases where it doesn't bother passing in a 7010 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7011 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7012 SelectionDAG &DAG, SDValue Ptr, 7013 SDValue OffsetOp) { 7014 // If the 'Offset' value isn't a constant, we can't handle this. 7015 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7016 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7017 if (OffsetOp.isUndef()) 7018 return InferPointerInfo(Info, DAG, Ptr); 7019 return Info; 7020 } 7021 7022 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7023 EVT VT, const SDLoc &dl, SDValue Chain, 7024 SDValue Ptr, SDValue Offset, 7025 MachinePointerInfo PtrInfo, EVT MemVT, 7026 Align Alignment, 7027 MachineMemOperand::Flags MMOFlags, 7028 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7029 assert(Chain.getValueType() == MVT::Other && 7030 "Invalid chain type"); 7031 7032 MMOFlags |= MachineMemOperand::MOLoad; 7033 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7034 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7035 // clients. 7036 if (PtrInfo.V.isNull()) 7037 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7038 7039 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7040 MachineFunction &MF = getMachineFunction(); 7041 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7042 Alignment, AAInfo, Ranges); 7043 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7044 } 7045 7046 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7047 EVT VT, const SDLoc &dl, SDValue Chain, 7048 SDValue Ptr, SDValue Offset, EVT MemVT, 7049 MachineMemOperand *MMO) { 7050 if (VT == MemVT) { 7051 ExtType = ISD::NON_EXTLOAD; 7052 } else if (ExtType == ISD::NON_EXTLOAD) { 7053 assert(VT == MemVT && "Non-extending load from different memory type!"); 7054 } else { 7055 // Extending load. 7056 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7057 "Should only be an extending load, not truncating!"); 7058 assert(VT.isInteger() == MemVT.isInteger() && 7059 "Cannot convert from FP to Int or Int -> FP!"); 7060 assert(VT.isVector() == MemVT.isVector() && 7061 "Cannot use an ext load to convert to or from a vector!"); 7062 assert((!VT.isVector() || 7063 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7064 "Cannot use an ext load to change the number of vector elements!"); 7065 } 7066 7067 bool Indexed = AM != ISD::UNINDEXED; 7068 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7069 7070 SDVTList VTs = Indexed ? 7071 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7072 SDValue Ops[] = { Chain, Ptr, Offset }; 7073 FoldingSetNodeID ID; 7074 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7075 ID.AddInteger(MemVT.getRawBits()); 7076 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7077 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7078 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7079 void *IP = nullptr; 7080 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7081 cast<LoadSDNode>(E)->refineAlignment(MMO); 7082 return SDValue(E, 0); 7083 } 7084 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7085 ExtType, MemVT, MMO); 7086 createOperands(N, Ops); 7087 7088 CSEMap.InsertNode(N, IP); 7089 InsertNode(N); 7090 SDValue V(N, 0); 7091 NewSDValueDbgMsg(V, "Creating new node: ", this); 7092 return V; 7093 } 7094 7095 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7096 SDValue Ptr, MachinePointerInfo PtrInfo, 7097 MaybeAlign Alignment, 7098 MachineMemOperand::Flags MMOFlags, 7099 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7100 SDValue Undef = getUNDEF(Ptr.getValueType()); 7101 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7102 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7103 } 7104 7105 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7106 SDValue Ptr, MachineMemOperand *MMO) { 7107 SDValue Undef = getUNDEF(Ptr.getValueType()); 7108 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7109 VT, MMO); 7110 } 7111 7112 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7113 EVT VT, SDValue Chain, SDValue Ptr, 7114 MachinePointerInfo PtrInfo, EVT MemVT, 7115 MaybeAlign Alignment, 7116 MachineMemOperand::Flags MMOFlags, 7117 const AAMDNodes &AAInfo) { 7118 SDValue Undef = getUNDEF(Ptr.getValueType()); 7119 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7120 MemVT, Alignment, MMOFlags, AAInfo); 7121 } 7122 7123 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7124 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7125 MachineMemOperand *MMO) { 7126 SDValue Undef = getUNDEF(Ptr.getValueType()); 7127 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7128 MemVT, MMO); 7129 } 7130 7131 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7132 SDValue Base, SDValue Offset, 7133 ISD::MemIndexedMode AM) { 7134 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7135 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7136 // Don't propagate the invariant or dereferenceable flags. 7137 auto MMOFlags = 7138 LD->getMemOperand()->getFlags() & 7139 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7140 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7141 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7142 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7143 } 7144 7145 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7146 SDValue Ptr, MachinePointerInfo PtrInfo, 7147 Align Alignment, 7148 MachineMemOperand::Flags MMOFlags, 7149 const AAMDNodes &AAInfo) { 7150 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7151 7152 MMOFlags |= MachineMemOperand::MOStore; 7153 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7154 7155 if (PtrInfo.V.isNull()) 7156 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7157 7158 MachineFunction &MF = getMachineFunction(); 7159 uint64_t Size = 7160 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7161 MachineMemOperand *MMO = 7162 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7163 return getStore(Chain, dl, Val, Ptr, MMO); 7164 } 7165 7166 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7167 SDValue Ptr, MachineMemOperand *MMO) { 7168 assert(Chain.getValueType() == MVT::Other && 7169 "Invalid chain type"); 7170 EVT VT = Val.getValueType(); 7171 SDVTList VTs = getVTList(MVT::Other); 7172 SDValue Undef = getUNDEF(Ptr.getValueType()); 7173 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7174 FoldingSetNodeID ID; 7175 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7176 ID.AddInteger(VT.getRawBits()); 7177 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7178 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7179 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7180 void *IP = nullptr; 7181 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7182 cast<StoreSDNode>(E)->refineAlignment(MMO); 7183 return SDValue(E, 0); 7184 } 7185 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7186 ISD::UNINDEXED, false, VT, MMO); 7187 createOperands(N, Ops); 7188 7189 CSEMap.InsertNode(N, IP); 7190 InsertNode(N); 7191 SDValue V(N, 0); 7192 NewSDValueDbgMsg(V, "Creating new node: ", this); 7193 return V; 7194 } 7195 7196 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7197 SDValue Ptr, MachinePointerInfo PtrInfo, 7198 EVT SVT, Align Alignment, 7199 MachineMemOperand::Flags MMOFlags, 7200 const AAMDNodes &AAInfo) { 7201 assert(Chain.getValueType() == MVT::Other && 7202 "Invalid chain type"); 7203 7204 MMOFlags |= MachineMemOperand::MOStore; 7205 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7206 7207 if (PtrInfo.V.isNull()) 7208 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7209 7210 MachineFunction &MF = getMachineFunction(); 7211 MachineMemOperand *MMO = MF.getMachineMemOperand( 7212 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7213 Alignment, AAInfo); 7214 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7215 } 7216 7217 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7218 SDValue Ptr, EVT SVT, 7219 MachineMemOperand *MMO) { 7220 EVT VT = Val.getValueType(); 7221 7222 assert(Chain.getValueType() == MVT::Other && 7223 "Invalid chain type"); 7224 if (VT == SVT) 7225 return getStore(Chain, dl, Val, Ptr, MMO); 7226 7227 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7228 "Should only be a truncating store, not extending!"); 7229 assert(VT.isInteger() == SVT.isInteger() && 7230 "Can't do FP-INT conversion!"); 7231 assert(VT.isVector() == SVT.isVector() && 7232 "Cannot use trunc store to convert to or from a vector!"); 7233 assert((!VT.isVector() || 7234 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7235 "Cannot use trunc store to change the number of vector elements!"); 7236 7237 SDVTList VTs = getVTList(MVT::Other); 7238 SDValue Undef = getUNDEF(Ptr.getValueType()); 7239 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7240 FoldingSetNodeID ID; 7241 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7242 ID.AddInteger(SVT.getRawBits()); 7243 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7244 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7245 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7246 void *IP = nullptr; 7247 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7248 cast<StoreSDNode>(E)->refineAlignment(MMO); 7249 return SDValue(E, 0); 7250 } 7251 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7252 ISD::UNINDEXED, true, SVT, MMO); 7253 createOperands(N, Ops); 7254 7255 CSEMap.InsertNode(N, IP); 7256 InsertNode(N); 7257 SDValue V(N, 0); 7258 NewSDValueDbgMsg(V, "Creating new node: ", this); 7259 return V; 7260 } 7261 7262 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7263 SDValue Base, SDValue Offset, 7264 ISD::MemIndexedMode AM) { 7265 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7266 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7267 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7268 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7269 FoldingSetNodeID ID; 7270 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7271 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7272 ID.AddInteger(ST->getRawSubclassData()); 7273 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7274 void *IP = nullptr; 7275 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7276 return SDValue(E, 0); 7277 7278 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7279 ST->isTruncatingStore(), ST->getMemoryVT(), 7280 ST->getMemOperand()); 7281 createOperands(N, Ops); 7282 7283 CSEMap.InsertNode(N, IP); 7284 InsertNode(N); 7285 SDValue V(N, 0); 7286 NewSDValueDbgMsg(V, "Creating new node: ", this); 7287 return V; 7288 } 7289 7290 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7291 SDValue Base, SDValue Offset, SDValue Mask, 7292 SDValue PassThru, EVT MemVT, 7293 MachineMemOperand *MMO, 7294 ISD::MemIndexedMode AM, 7295 ISD::LoadExtType ExtTy, bool isExpanding) { 7296 bool Indexed = AM != ISD::UNINDEXED; 7297 assert((Indexed || Offset.isUndef()) && 7298 "Unindexed masked load with an offset!"); 7299 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7300 : getVTList(VT, MVT::Other); 7301 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7302 FoldingSetNodeID ID; 7303 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7304 ID.AddInteger(MemVT.getRawBits()); 7305 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7306 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7307 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7308 void *IP = nullptr; 7309 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7310 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7311 return SDValue(E, 0); 7312 } 7313 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7314 AM, ExtTy, isExpanding, MemVT, MMO); 7315 createOperands(N, Ops); 7316 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 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7325 SDValue Base, SDValue Offset, 7326 ISD::MemIndexedMode AM) { 7327 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7328 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7329 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7330 Offset, LD->getMask(), LD->getPassThru(), 7331 LD->getMemoryVT(), LD->getMemOperand(), AM, 7332 LD->getExtensionType(), LD->isExpandingLoad()); 7333 } 7334 7335 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7336 SDValue Val, SDValue Base, SDValue Offset, 7337 SDValue Mask, EVT MemVT, 7338 MachineMemOperand *MMO, 7339 ISD::MemIndexedMode AM, bool IsTruncating, 7340 bool IsCompressing) { 7341 assert(Chain.getValueType() == MVT::Other && 7342 "Invalid chain type"); 7343 bool Indexed = AM != ISD::UNINDEXED; 7344 assert((Indexed || Offset.isUndef()) && 7345 "Unindexed masked store with an offset!"); 7346 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7347 : getVTList(MVT::Other); 7348 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7349 FoldingSetNodeID ID; 7350 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7351 ID.AddInteger(MemVT.getRawBits()); 7352 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7353 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7354 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7355 void *IP = nullptr; 7356 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7357 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7358 return SDValue(E, 0); 7359 } 7360 auto *N = 7361 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7362 IsTruncating, IsCompressing, MemVT, MMO); 7363 createOperands(N, Ops); 7364 7365 CSEMap.InsertNode(N, IP); 7366 InsertNode(N); 7367 SDValue V(N, 0); 7368 NewSDValueDbgMsg(V, "Creating new node: ", this); 7369 return V; 7370 } 7371 7372 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7373 SDValue Base, SDValue Offset, 7374 ISD::MemIndexedMode AM) { 7375 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7376 assert(ST->getOffset().isUndef() && 7377 "Masked store is already a indexed store!"); 7378 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7379 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7380 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7381 } 7382 7383 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7384 ArrayRef<SDValue> Ops, 7385 MachineMemOperand *MMO, 7386 ISD::MemIndexType IndexType, 7387 ISD::LoadExtType ExtTy) { 7388 assert(Ops.size() == 6 && "Incompatible number of operands"); 7389 7390 FoldingSetNodeID ID; 7391 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7392 ID.AddInteger(VT.getRawBits()); 7393 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7394 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7395 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7396 void *IP = nullptr; 7397 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7398 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7399 return SDValue(E, 0); 7400 } 7401 7402 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7403 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7404 VTs, VT, MMO, IndexType, ExtTy); 7405 createOperands(N, Ops); 7406 7407 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7408 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7409 assert(N->getMask().getValueType().getVectorElementCount() == 7410 N->getValueType(0).getVectorElementCount() && 7411 "Vector width mismatch between mask and data"); 7412 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7413 N->getValueType(0).getVectorElementCount().isScalable() && 7414 "Scalable flags of index and data do not match"); 7415 assert(ElementCount::isKnownGE( 7416 N->getIndex().getValueType().getVectorElementCount(), 7417 N->getValueType(0).getVectorElementCount()) && 7418 "Vector width mismatch between index and data"); 7419 assert(isa<ConstantSDNode>(N->getScale()) && 7420 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7421 "Scale should be a constant power of 2"); 7422 7423 CSEMap.InsertNode(N, IP); 7424 InsertNode(N); 7425 SDValue V(N, 0); 7426 NewSDValueDbgMsg(V, "Creating new node: ", this); 7427 return V; 7428 } 7429 7430 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7431 ArrayRef<SDValue> Ops, 7432 MachineMemOperand *MMO, 7433 ISD::MemIndexType IndexType, 7434 bool IsTrunc) { 7435 assert(Ops.size() == 6 && "Incompatible number of operands"); 7436 7437 FoldingSetNodeID ID; 7438 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7439 ID.AddInteger(VT.getRawBits()); 7440 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7441 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7442 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7443 void *IP = nullptr; 7444 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7445 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7446 return SDValue(E, 0); 7447 } 7448 7449 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7450 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7451 VTs, VT, MMO, IndexType, IsTrunc); 7452 createOperands(N, Ops); 7453 7454 assert(N->getMask().getValueType().getVectorElementCount() == 7455 N->getValue().getValueType().getVectorElementCount() && 7456 "Vector width mismatch between mask and data"); 7457 assert( 7458 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7459 N->getValue().getValueType().getVectorElementCount().isScalable() && 7460 "Scalable flags of index and data do not match"); 7461 assert(ElementCount::isKnownGE( 7462 N->getIndex().getValueType().getVectorElementCount(), 7463 N->getValue().getValueType().getVectorElementCount()) && 7464 "Vector width mismatch between index and data"); 7465 assert(isa<ConstantSDNode>(N->getScale()) && 7466 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7467 "Scale should be a constant power of 2"); 7468 7469 CSEMap.InsertNode(N, IP); 7470 InsertNode(N); 7471 SDValue V(N, 0); 7472 NewSDValueDbgMsg(V, "Creating new node: ", this); 7473 return V; 7474 } 7475 7476 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7477 // select undef, T, F --> T (if T is a constant), otherwise F 7478 // select, ?, undef, F --> F 7479 // select, ?, T, undef --> T 7480 if (Cond.isUndef()) 7481 return isConstantValueOfAnyType(T) ? T : F; 7482 if (T.isUndef()) 7483 return F; 7484 if (F.isUndef()) 7485 return T; 7486 7487 // select true, T, F --> T 7488 // select false, T, F --> F 7489 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7490 return CondC->isNullValue() ? F : T; 7491 7492 // TODO: This should simplify VSELECT with constant condition using something 7493 // like this (but check boolean contents to be complete?): 7494 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7495 // return T; 7496 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7497 // return F; 7498 7499 // select ?, T, T --> T 7500 if (T == F) 7501 return T; 7502 7503 return SDValue(); 7504 } 7505 7506 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7507 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7508 if (X.isUndef()) 7509 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7510 // shift X, undef --> undef (because it may shift by the bitwidth) 7511 if (Y.isUndef()) 7512 return getUNDEF(X.getValueType()); 7513 7514 // shift 0, Y --> 0 7515 // shift X, 0 --> X 7516 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7517 return X; 7518 7519 // shift X, C >= bitwidth(X) --> undef 7520 // All vector elements must be too big (or undef) to avoid partial undefs. 7521 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7522 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7523 }; 7524 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7525 return getUNDEF(X.getValueType()); 7526 7527 return SDValue(); 7528 } 7529 7530 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7531 SDNodeFlags Flags) { 7532 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7533 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7534 // operation is poison. That result can be relaxed to undef. 7535 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7536 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7537 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7538 (YC && YC->getValueAPF().isNaN()); 7539 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7540 (YC && YC->getValueAPF().isInfinity()); 7541 7542 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7543 return getUNDEF(X.getValueType()); 7544 7545 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7546 return getUNDEF(X.getValueType()); 7547 7548 if (!YC) 7549 return SDValue(); 7550 7551 // X + -0.0 --> X 7552 if (Opcode == ISD::FADD) 7553 if (YC->getValueAPF().isNegZero()) 7554 return X; 7555 7556 // X - +0.0 --> X 7557 if (Opcode == ISD::FSUB) 7558 if (YC->getValueAPF().isPosZero()) 7559 return X; 7560 7561 // X * 1.0 --> X 7562 // X / 1.0 --> X 7563 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7564 if (YC->getValueAPF().isExactlyValue(1.0)) 7565 return X; 7566 7567 // X * 0.0 --> 0.0 7568 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7569 if (YC->getValueAPF().isZero()) 7570 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7571 7572 return SDValue(); 7573 } 7574 7575 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7576 SDValue Ptr, SDValue SV, unsigned Align) { 7577 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7578 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7579 } 7580 7581 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7582 ArrayRef<SDUse> Ops) { 7583 switch (Ops.size()) { 7584 case 0: return getNode(Opcode, DL, VT); 7585 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7586 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7587 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7588 default: break; 7589 } 7590 7591 // Copy from an SDUse array into an SDValue array for use with 7592 // the regular getNode logic. 7593 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7594 return getNode(Opcode, DL, VT, NewOps); 7595 } 7596 7597 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7598 ArrayRef<SDValue> Ops) { 7599 SDNodeFlags Flags; 7600 if (Inserter) 7601 Flags = Inserter->getFlags(); 7602 return getNode(Opcode, DL, VT, Ops, Flags); 7603 } 7604 7605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7606 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7607 unsigned NumOps = Ops.size(); 7608 switch (NumOps) { 7609 case 0: return getNode(Opcode, DL, VT); 7610 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7611 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7612 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7613 default: break; 7614 } 7615 7616 switch (Opcode) { 7617 default: break; 7618 case ISD::BUILD_VECTOR: 7619 // Attempt to simplify BUILD_VECTOR. 7620 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7621 return V; 7622 break; 7623 case ISD::CONCAT_VECTORS: 7624 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7625 return V; 7626 break; 7627 case ISD::SELECT_CC: 7628 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7629 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7630 "LHS and RHS of condition must have same type!"); 7631 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7632 "True and False arms of SelectCC must have same type!"); 7633 assert(Ops[2].getValueType() == VT && 7634 "select_cc node must be of same type as true and false value!"); 7635 break; 7636 case ISD::BR_CC: 7637 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7638 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7639 "LHS/RHS of comparison should match types!"); 7640 break; 7641 } 7642 7643 // Memoize nodes. 7644 SDNode *N; 7645 SDVTList VTs = getVTList(VT); 7646 7647 if (VT != MVT::Glue) { 7648 FoldingSetNodeID ID; 7649 AddNodeIDNode(ID, Opcode, VTs, Ops); 7650 void *IP = nullptr; 7651 7652 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7653 return SDValue(E, 0); 7654 7655 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7656 createOperands(N, Ops); 7657 7658 CSEMap.InsertNode(N, IP); 7659 } else { 7660 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7661 createOperands(N, Ops); 7662 } 7663 7664 N->setFlags(Flags); 7665 InsertNode(N); 7666 SDValue V(N, 0); 7667 NewSDValueDbgMsg(V, "Creating new node: ", this); 7668 return V; 7669 } 7670 7671 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7672 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7673 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7674 } 7675 7676 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7677 ArrayRef<SDValue> Ops) { 7678 SDNodeFlags Flags; 7679 if (Inserter) 7680 Flags = Inserter->getFlags(); 7681 return getNode(Opcode, DL, VTList, Ops, Flags); 7682 } 7683 7684 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7685 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7686 if (VTList.NumVTs == 1) 7687 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7688 7689 switch (Opcode) { 7690 case ISD::STRICT_FP_EXTEND: 7691 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7692 "Invalid STRICT_FP_EXTEND!"); 7693 assert(VTList.VTs[0].isFloatingPoint() && 7694 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7695 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7696 "STRICT_FP_EXTEND result type should be vector iff the operand " 7697 "type is vector!"); 7698 assert((!VTList.VTs[0].isVector() || 7699 VTList.VTs[0].getVectorNumElements() == 7700 Ops[1].getValueType().getVectorNumElements()) && 7701 "Vector element count mismatch!"); 7702 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7703 "Invalid fpext node, dst <= src!"); 7704 break; 7705 case ISD::STRICT_FP_ROUND: 7706 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7707 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7708 "STRICT_FP_ROUND result type should be vector iff the operand " 7709 "type is vector!"); 7710 assert((!VTList.VTs[0].isVector() || 7711 VTList.VTs[0].getVectorNumElements() == 7712 Ops[1].getValueType().getVectorNumElements()) && 7713 "Vector element count mismatch!"); 7714 assert(VTList.VTs[0].isFloatingPoint() && 7715 Ops[1].getValueType().isFloatingPoint() && 7716 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7717 isa<ConstantSDNode>(Ops[2]) && 7718 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7719 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7720 "Invalid STRICT_FP_ROUND!"); 7721 break; 7722 #if 0 7723 // FIXME: figure out how to safely handle things like 7724 // int foo(int x) { return 1 << (x & 255); } 7725 // int bar() { return foo(256); } 7726 case ISD::SRA_PARTS: 7727 case ISD::SRL_PARTS: 7728 case ISD::SHL_PARTS: 7729 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7730 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7731 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7732 else if (N3.getOpcode() == ISD::AND) 7733 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7734 // If the and is only masking out bits that cannot effect the shift, 7735 // eliminate the and. 7736 unsigned NumBits = VT.getScalarSizeInBits()*2; 7737 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7738 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7739 } 7740 break; 7741 #endif 7742 } 7743 7744 // Memoize the node unless it returns a flag. 7745 SDNode *N; 7746 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7747 FoldingSetNodeID ID; 7748 AddNodeIDNode(ID, Opcode, VTList, Ops); 7749 void *IP = nullptr; 7750 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7751 return SDValue(E, 0); 7752 7753 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7754 createOperands(N, Ops); 7755 CSEMap.InsertNode(N, IP); 7756 } else { 7757 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7758 createOperands(N, Ops); 7759 } 7760 7761 N->setFlags(Flags); 7762 InsertNode(N); 7763 SDValue V(N, 0); 7764 NewSDValueDbgMsg(V, "Creating new node: ", this); 7765 return V; 7766 } 7767 7768 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7769 SDVTList VTList) { 7770 return getNode(Opcode, DL, VTList, None); 7771 } 7772 7773 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7774 SDValue N1) { 7775 SDValue Ops[] = { N1 }; 7776 return getNode(Opcode, DL, VTList, Ops); 7777 } 7778 7779 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7780 SDValue N1, SDValue N2) { 7781 SDValue Ops[] = { N1, N2 }; 7782 return getNode(Opcode, DL, VTList, Ops); 7783 } 7784 7785 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7786 SDValue N1, SDValue N2, SDValue N3) { 7787 SDValue Ops[] = { N1, N2, N3 }; 7788 return getNode(Opcode, DL, VTList, Ops); 7789 } 7790 7791 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7792 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7793 SDValue Ops[] = { N1, N2, N3, N4 }; 7794 return getNode(Opcode, DL, VTList, Ops); 7795 } 7796 7797 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7798 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7799 SDValue N5) { 7800 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7801 return getNode(Opcode, DL, VTList, Ops); 7802 } 7803 7804 SDVTList SelectionDAG::getVTList(EVT VT) { 7805 return makeVTList(SDNode::getValueTypeList(VT), 1); 7806 } 7807 7808 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7809 FoldingSetNodeID ID; 7810 ID.AddInteger(2U); 7811 ID.AddInteger(VT1.getRawBits()); 7812 ID.AddInteger(VT2.getRawBits()); 7813 7814 void *IP = nullptr; 7815 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7816 if (!Result) { 7817 EVT *Array = Allocator.Allocate<EVT>(2); 7818 Array[0] = VT1; 7819 Array[1] = VT2; 7820 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7821 VTListMap.InsertNode(Result, IP); 7822 } 7823 return Result->getSDVTList(); 7824 } 7825 7826 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7827 FoldingSetNodeID ID; 7828 ID.AddInteger(3U); 7829 ID.AddInteger(VT1.getRawBits()); 7830 ID.AddInteger(VT2.getRawBits()); 7831 ID.AddInteger(VT3.getRawBits()); 7832 7833 void *IP = nullptr; 7834 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7835 if (!Result) { 7836 EVT *Array = Allocator.Allocate<EVT>(3); 7837 Array[0] = VT1; 7838 Array[1] = VT2; 7839 Array[2] = VT3; 7840 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7841 VTListMap.InsertNode(Result, IP); 7842 } 7843 return Result->getSDVTList(); 7844 } 7845 7846 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7847 FoldingSetNodeID ID; 7848 ID.AddInteger(4U); 7849 ID.AddInteger(VT1.getRawBits()); 7850 ID.AddInteger(VT2.getRawBits()); 7851 ID.AddInteger(VT3.getRawBits()); 7852 ID.AddInteger(VT4.getRawBits()); 7853 7854 void *IP = nullptr; 7855 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7856 if (!Result) { 7857 EVT *Array = Allocator.Allocate<EVT>(4); 7858 Array[0] = VT1; 7859 Array[1] = VT2; 7860 Array[2] = VT3; 7861 Array[3] = VT4; 7862 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7863 VTListMap.InsertNode(Result, IP); 7864 } 7865 return Result->getSDVTList(); 7866 } 7867 7868 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7869 unsigned NumVTs = VTs.size(); 7870 FoldingSetNodeID ID; 7871 ID.AddInteger(NumVTs); 7872 for (unsigned index = 0; index < NumVTs; index++) { 7873 ID.AddInteger(VTs[index].getRawBits()); 7874 } 7875 7876 void *IP = nullptr; 7877 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7878 if (!Result) { 7879 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 7880 llvm::copy(VTs, Array); 7881 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 7882 VTListMap.InsertNode(Result, IP); 7883 } 7884 return Result->getSDVTList(); 7885 } 7886 7887 7888 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 7889 /// specified operands. If the resultant node already exists in the DAG, 7890 /// this does not modify the specified node, instead it returns the node that 7891 /// already exists. If the resultant node does not exist in the DAG, the 7892 /// input node is returned. As a degenerate case, if you specify the same 7893 /// input operands as the node already has, the input node is returned. 7894 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 7895 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 7896 7897 // Check to see if there is no change. 7898 if (Op == N->getOperand(0)) return N; 7899 7900 // See if the modified node already exists. 7901 void *InsertPos = nullptr; 7902 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 7903 return Existing; 7904 7905 // Nope it doesn't. Remove the node from its current place in the maps. 7906 if (InsertPos) 7907 if (!RemoveNodeFromCSEMaps(N)) 7908 InsertPos = nullptr; 7909 7910 // Now we update the operands. 7911 N->OperandList[0].set(Op); 7912 7913 updateDivergence(N); 7914 // If this gets put into a CSE map, add it. 7915 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7916 return N; 7917 } 7918 7919 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 7920 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 7921 7922 // Check to see if there is no change. 7923 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 7924 return N; // No operands changed, just return the input node. 7925 7926 // See if the modified node already exists. 7927 void *InsertPos = nullptr; 7928 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 7929 return Existing; 7930 7931 // Nope it doesn't. Remove the node from its current place in the maps. 7932 if (InsertPos) 7933 if (!RemoveNodeFromCSEMaps(N)) 7934 InsertPos = nullptr; 7935 7936 // Now we update the operands. 7937 if (N->OperandList[0] != Op1) 7938 N->OperandList[0].set(Op1); 7939 if (N->OperandList[1] != Op2) 7940 N->OperandList[1].set(Op2); 7941 7942 updateDivergence(N); 7943 // If this gets put into a CSE map, add it. 7944 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7945 return N; 7946 } 7947 7948 SDNode *SelectionDAG:: 7949 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 7950 SDValue Ops[] = { Op1, Op2, Op3 }; 7951 return UpdateNodeOperands(N, Ops); 7952 } 7953 7954 SDNode *SelectionDAG:: 7955 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7956 SDValue Op3, SDValue Op4) { 7957 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 7958 return UpdateNodeOperands(N, Ops); 7959 } 7960 7961 SDNode *SelectionDAG:: 7962 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 7963 SDValue Op3, SDValue Op4, SDValue Op5) { 7964 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 7965 return UpdateNodeOperands(N, Ops); 7966 } 7967 7968 SDNode *SelectionDAG:: 7969 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 7970 unsigned NumOps = Ops.size(); 7971 assert(N->getNumOperands() == NumOps && 7972 "Update with wrong number of operands"); 7973 7974 // If no operands changed just return the input node. 7975 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 7976 return N; 7977 7978 // See if the modified node already exists. 7979 void *InsertPos = nullptr; 7980 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 7981 return Existing; 7982 7983 // Nope it doesn't. Remove the node from its current place in the maps. 7984 if (InsertPos) 7985 if (!RemoveNodeFromCSEMaps(N)) 7986 InsertPos = nullptr; 7987 7988 // Now we update the operands. 7989 for (unsigned i = 0; i != NumOps; ++i) 7990 if (N->OperandList[i] != Ops[i]) 7991 N->OperandList[i].set(Ops[i]); 7992 7993 updateDivergence(N); 7994 // If this gets put into a CSE map, add it. 7995 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 7996 return N; 7997 } 7998 7999 /// DropOperands - Release the operands and set this node to have 8000 /// zero operands. 8001 void SDNode::DropOperands() { 8002 // Unlike the code in MorphNodeTo that does this, we don't need to 8003 // watch for dead nodes here. 8004 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8005 SDUse &Use = *I++; 8006 Use.set(SDValue()); 8007 } 8008 } 8009 8010 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8011 ArrayRef<MachineMemOperand *> NewMemRefs) { 8012 if (NewMemRefs.empty()) { 8013 N->clearMemRefs(); 8014 return; 8015 } 8016 8017 // Check if we can avoid allocating by storing a single reference directly. 8018 if (NewMemRefs.size() == 1) { 8019 N->MemRefs = NewMemRefs[0]; 8020 N->NumMemRefs = 1; 8021 return; 8022 } 8023 8024 MachineMemOperand **MemRefsBuffer = 8025 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8026 llvm::copy(NewMemRefs, MemRefsBuffer); 8027 N->MemRefs = MemRefsBuffer; 8028 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8029 } 8030 8031 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8032 /// machine opcode. 8033 /// 8034 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8035 EVT VT) { 8036 SDVTList VTs = getVTList(VT); 8037 return SelectNodeTo(N, MachineOpc, VTs, None); 8038 } 8039 8040 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8041 EVT VT, SDValue Op1) { 8042 SDVTList VTs = getVTList(VT); 8043 SDValue Ops[] = { Op1 }; 8044 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8045 } 8046 8047 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8048 EVT VT, SDValue Op1, 8049 SDValue Op2) { 8050 SDVTList VTs = getVTList(VT); 8051 SDValue Ops[] = { Op1, Op2 }; 8052 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8053 } 8054 8055 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8056 EVT VT, SDValue Op1, 8057 SDValue Op2, SDValue Op3) { 8058 SDVTList VTs = getVTList(VT); 8059 SDValue Ops[] = { Op1, Op2, Op3 }; 8060 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8061 } 8062 8063 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8064 EVT VT, ArrayRef<SDValue> Ops) { 8065 SDVTList VTs = getVTList(VT); 8066 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8067 } 8068 8069 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8070 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8071 SDVTList VTs = getVTList(VT1, VT2); 8072 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8073 } 8074 8075 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8076 EVT VT1, EVT VT2) { 8077 SDVTList VTs = getVTList(VT1, VT2); 8078 return SelectNodeTo(N, MachineOpc, VTs, None); 8079 } 8080 8081 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8082 EVT VT1, EVT VT2, EVT VT3, 8083 ArrayRef<SDValue> Ops) { 8084 SDVTList VTs = getVTList(VT1, VT2, VT3); 8085 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8086 } 8087 8088 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8089 EVT VT1, EVT VT2, 8090 SDValue Op1, SDValue Op2) { 8091 SDVTList VTs = getVTList(VT1, VT2); 8092 SDValue Ops[] = { Op1, Op2 }; 8093 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8094 } 8095 8096 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8097 SDVTList VTs,ArrayRef<SDValue> Ops) { 8098 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8099 // Reset the NodeID to -1. 8100 New->setNodeId(-1); 8101 if (New != N) { 8102 ReplaceAllUsesWith(N, New); 8103 RemoveDeadNode(N); 8104 } 8105 return New; 8106 } 8107 8108 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8109 /// the line number information on the merged node since it is not possible to 8110 /// preserve the information that operation is associated with multiple lines. 8111 /// This will make the debugger working better at -O0, were there is a higher 8112 /// probability having other instructions associated with that line. 8113 /// 8114 /// For IROrder, we keep the smaller of the two 8115 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8116 DebugLoc NLoc = N->getDebugLoc(); 8117 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8118 N->setDebugLoc(DebugLoc()); 8119 } 8120 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8121 N->setIROrder(Order); 8122 return N; 8123 } 8124 8125 /// MorphNodeTo - This *mutates* the specified node to have the specified 8126 /// return type, opcode, and operands. 8127 /// 8128 /// Note that MorphNodeTo returns the resultant node. If there is already a 8129 /// node of the specified opcode and operands, it returns that node instead of 8130 /// the current one. Note that the SDLoc need not be the same. 8131 /// 8132 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8133 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8134 /// node, and because it doesn't require CSE recalculation for any of 8135 /// the node's users. 8136 /// 8137 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8138 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8139 /// the legalizer which maintain worklists that would need to be updated when 8140 /// deleting things. 8141 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8142 SDVTList VTs, ArrayRef<SDValue> Ops) { 8143 // If an identical node already exists, use it. 8144 void *IP = nullptr; 8145 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8146 FoldingSetNodeID ID; 8147 AddNodeIDNode(ID, Opc, VTs, Ops); 8148 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8149 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8150 } 8151 8152 if (!RemoveNodeFromCSEMaps(N)) 8153 IP = nullptr; 8154 8155 // Start the morphing. 8156 N->NodeType = Opc; 8157 N->ValueList = VTs.VTs; 8158 N->NumValues = VTs.NumVTs; 8159 8160 // Clear the operands list, updating used nodes to remove this from their 8161 // use list. Keep track of any operands that become dead as a result. 8162 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8163 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8164 SDUse &Use = *I++; 8165 SDNode *Used = Use.getNode(); 8166 Use.set(SDValue()); 8167 if (Used->use_empty()) 8168 DeadNodeSet.insert(Used); 8169 } 8170 8171 // For MachineNode, initialize the memory references information. 8172 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8173 MN->clearMemRefs(); 8174 8175 // Swap for an appropriately sized array from the recycler. 8176 removeOperands(N); 8177 createOperands(N, Ops); 8178 8179 // Delete any nodes that are still dead after adding the uses for the 8180 // new operands. 8181 if (!DeadNodeSet.empty()) { 8182 SmallVector<SDNode *, 16> DeadNodes; 8183 for (SDNode *N : DeadNodeSet) 8184 if (N->use_empty()) 8185 DeadNodes.push_back(N); 8186 RemoveDeadNodes(DeadNodes); 8187 } 8188 8189 if (IP) 8190 CSEMap.InsertNode(N, IP); // Memoize the new node. 8191 return N; 8192 } 8193 8194 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8195 unsigned OrigOpc = Node->getOpcode(); 8196 unsigned NewOpc; 8197 switch (OrigOpc) { 8198 default: 8199 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8200 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8201 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8202 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8203 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8204 #include "llvm/IR/ConstrainedOps.def" 8205 } 8206 8207 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8208 8209 // We're taking this node out of the chain, so we need to re-link things. 8210 SDValue InputChain = Node->getOperand(0); 8211 SDValue OutputChain = SDValue(Node, 1); 8212 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8213 8214 SmallVector<SDValue, 3> Ops; 8215 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8216 Ops.push_back(Node->getOperand(i)); 8217 8218 SDVTList VTs = getVTList(Node->getValueType(0)); 8219 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8220 8221 // MorphNodeTo can operate in two ways: if an existing node with the 8222 // specified operands exists, it can just return it. Otherwise, it 8223 // updates the node in place to have the requested operands. 8224 if (Res == Node) { 8225 // If we updated the node in place, reset the node ID. To the isel, 8226 // this should be just like a newly allocated machine node. 8227 Res->setNodeId(-1); 8228 } else { 8229 ReplaceAllUsesWith(Node, Res); 8230 RemoveDeadNode(Node); 8231 } 8232 8233 return Res; 8234 } 8235 8236 /// getMachineNode - These are used for target selectors to create a new node 8237 /// with specified return type(s), MachineInstr opcode, and operands. 8238 /// 8239 /// Note that getMachineNode returns the resultant node. If there is already a 8240 /// node of the specified opcode and operands, it returns that node instead of 8241 /// the current one. 8242 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8243 EVT VT) { 8244 SDVTList VTs = getVTList(VT); 8245 return getMachineNode(Opcode, dl, VTs, None); 8246 } 8247 8248 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8249 EVT VT, SDValue Op1) { 8250 SDVTList VTs = getVTList(VT); 8251 SDValue Ops[] = { Op1 }; 8252 return getMachineNode(Opcode, dl, VTs, Ops); 8253 } 8254 8255 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8256 EVT VT, SDValue Op1, SDValue Op2) { 8257 SDVTList VTs = getVTList(VT); 8258 SDValue Ops[] = { Op1, Op2 }; 8259 return getMachineNode(Opcode, dl, VTs, Ops); 8260 } 8261 8262 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8263 EVT VT, SDValue Op1, SDValue Op2, 8264 SDValue Op3) { 8265 SDVTList VTs = getVTList(VT); 8266 SDValue Ops[] = { Op1, Op2, Op3 }; 8267 return getMachineNode(Opcode, dl, VTs, Ops); 8268 } 8269 8270 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8271 EVT VT, ArrayRef<SDValue> Ops) { 8272 SDVTList VTs = getVTList(VT); 8273 return getMachineNode(Opcode, dl, VTs, Ops); 8274 } 8275 8276 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8277 EVT VT1, EVT VT2, SDValue Op1, 8278 SDValue Op2) { 8279 SDVTList VTs = getVTList(VT1, VT2); 8280 SDValue Ops[] = { Op1, Op2 }; 8281 return getMachineNode(Opcode, dl, VTs, Ops); 8282 } 8283 8284 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8285 EVT VT1, EVT VT2, SDValue Op1, 8286 SDValue Op2, SDValue Op3) { 8287 SDVTList VTs = getVTList(VT1, VT2); 8288 SDValue Ops[] = { Op1, Op2, Op3 }; 8289 return getMachineNode(Opcode, dl, VTs, Ops); 8290 } 8291 8292 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8293 EVT VT1, EVT VT2, 8294 ArrayRef<SDValue> Ops) { 8295 SDVTList VTs = getVTList(VT1, VT2); 8296 return getMachineNode(Opcode, dl, VTs, Ops); 8297 } 8298 8299 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8300 EVT VT1, EVT VT2, EVT VT3, 8301 SDValue Op1, SDValue Op2) { 8302 SDVTList VTs = getVTList(VT1, VT2, VT3); 8303 SDValue Ops[] = { Op1, Op2 }; 8304 return getMachineNode(Opcode, dl, VTs, Ops); 8305 } 8306 8307 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8308 EVT VT1, EVT VT2, EVT VT3, 8309 SDValue Op1, SDValue Op2, 8310 SDValue Op3) { 8311 SDVTList VTs = getVTList(VT1, VT2, VT3); 8312 SDValue Ops[] = { Op1, Op2, Op3 }; 8313 return getMachineNode(Opcode, dl, VTs, Ops); 8314 } 8315 8316 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8317 EVT VT1, EVT VT2, EVT VT3, 8318 ArrayRef<SDValue> Ops) { 8319 SDVTList VTs = getVTList(VT1, VT2, VT3); 8320 return getMachineNode(Opcode, dl, VTs, Ops); 8321 } 8322 8323 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8324 ArrayRef<EVT> ResultTys, 8325 ArrayRef<SDValue> Ops) { 8326 SDVTList VTs = getVTList(ResultTys); 8327 return getMachineNode(Opcode, dl, VTs, Ops); 8328 } 8329 8330 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8331 SDVTList VTs, 8332 ArrayRef<SDValue> Ops) { 8333 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8334 MachineSDNode *N; 8335 void *IP = nullptr; 8336 8337 if (DoCSE) { 8338 FoldingSetNodeID ID; 8339 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8340 IP = nullptr; 8341 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8342 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8343 } 8344 } 8345 8346 // Allocate a new MachineSDNode. 8347 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8348 createOperands(N, Ops); 8349 8350 if (DoCSE) 8351 CSEMap.InsertNode(N, IP); 8352 8353 InsertNode(N); 8354 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8355 return N; 8356 } 8357 8358 /// getTargetExtractSubreg - A convenience function for creating 8359 /// TargetOpcode::EXTRACT_SUBREG nodes. 8360 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8361 SDValue Operand) { 8362 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8363 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8364 VT, Operand, SRIdxVal); 8365 return SDValue(Subreg, 0); 8366 } 8367 8368 /// getTargetInsertSubreg - A convenience function for creating 8369 /// TargetOpcode::INSERT_SUBREG nodes. 8370 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8371 SDValue Operand, SDValue Subreg) { 8372 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8373 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8374 VT, Operand, Subreg, SRIdxVal); 8375 return SDValue(Result, 0); 8376 } 8377 8378 /// getNodeIfExists - Get the specified node if it's already available, or 8379 /// else return NULL. 8380 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8381 ArrayRef<SDValue> Ops) { 8382 SDNodeFlags Flags; 8383 if (Inserter) 8384 Flags = Inserter->getFlags(); 8385 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8386 } 8387 8388 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8389 ArrayRef<SDValue> Ops, 8390 const SDNodeFlags Flags) { 8391 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8392 FoldingSetNodeID ID; 8393 AddNodeIDNode(ID, Opcode, VTList, Ops); 8394 void *IP = nullptr; 8395 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8396 E->intersectFlagsWith(Flags); 8397 return E; 8398 } 8399 } 8400 return nullptr; 8401 } 8402 8403 /// doesNodeExist - Check if a node exists without modifying its flags. 8404 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8405 ArrayRef<SDValue> Ops) { 8406 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8407 FoldingSetNodeID ID; 8408 AddNodeIDNode(ID, Opcode, VTList, Ops); 8409 void *IP = nullptr; 8410 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8411 return true; 8412 } 8413 return false; 8414 } 8415 8416 /// getDbgValue - Creates a SDDbgValue node. 8417 /// 8418 /// SDNode 8419 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8420 SDNode *N, unsigned R, bool IsIndirect, 8421 const DebugLoc &DL, unsigned O) { 8422 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8423 "Expected inlined-at fields to agree"); 8424 return new (DbgInfo->getAlloc()) 8425 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O); 8426 } 8427 8428 /// Constant 8429 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8430 DIExpression *Expr, 8431 const Value *C, 8432 const DebugLoc &DL, unsigned O) { 8433 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8434 "Expected inlined-at fields to agree"); 8435 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O); 8436 } 8437 8438 /// FrameIndex 8439 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8440 DIExpression *Expr, unsigned FI, 8441 bool IsIndirect, 8442 const DebugLoc &DL, 8443 unsigned O) { 8444 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8445 "Expected inlined-at fields to agree"); 8446 return new (DbgInfo->getAlloc()) 8447 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX); 8448 } 8449 8450 /// VReg 8451 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, 8452 DIExpression *Expr, 8453 unsigned VReg, bool IsIndirect, 8454 const DebugLoc &DL, unsigned O) { 8455 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8456 "Expected inlined-at fields to agree"); 8457 return new (DbgInfo->getAlloc()) 8458 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG); 8459 } 8460 8461 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8462 unsigned OffsetInBits, unsigned SizeInBits, 8463 bool InvalidateDbg) { 8464 SDNode *FromNode = From.getNode(); 8465 SDNode *ToNode = To.getNode(); 8466 assert(FromNode && ToNode && "Can't modify dbg values"); 8467 8468 // PR35338 8469 // TODO: assert(From != To && "Redundant dbg value transfer"); 8470 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8471 if (From == To || FromNode == ToNode) 8472 return; 8473 8474 if (!FromNode->getHasDebugValue()) 8475 return; 8476 8477 SmallVector<SDDbgValue *, 2> ClonedDVs; 8478 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8479 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated()) 8480 continue; 8481 8482 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8483 8484 // Just transfer the dbg value attached to From. 8485 if (Dbg->getResNo() != From.getResNo()) 8486 continue; 8487 8488 DIVariable *Var = Dbg->getVariable(); 8489 auto *Expr = Dbg->getExpression(); 8490 // If a fragment is requested, update the expression. 8491 if (SizeInBits) { 8492 // When splitting a larger (e.g., sign-extended) value whose 8493 // lower bits are described with an SDDbgValue, do not attempt 8494 // to transfer the SDDbgValue to the upper bits. 8495 if (auto FI = Expr->getFragmentInfo()) 8496 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8497 continue; 8498 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8499 SizeInBits); 8500 if (!Fragment) 8501 continue; 8502 Expr = *Fragment; 8503 } 8504 // Clone the SDDbgValue and move it to To. 8505 SDDbgValue *Clone = getDbgValue( 8506 Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(), 8507 std::max(ToNode->getIROrder(), Dbg->getOrder())); 8508 ClonedDVs.push_back(Clone); 8509 8510 if (InvalidateDbg) { 8511 // Invalidate value and indicate the SDDbgValue should not be emitted. 8512 Dbg->setIsInvalidated(); 8513 Dbg->setIsEmitted(); 8514 } 8515 } 8516 8517 for (SDDbgValue *Dbg : ClonedDVs) 8518 AddDbgValue(Dbg, ToNode, false); 8519 } 8520 8521 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8522 if (!N.getHasDebugValue()) 8523 return; 8524 8525 SmallVector<SDDbgValue *, 2> ClonedDVs; 8526 for (auto DV : GetDbgValues(&N)) { 8527 if (DV->isInvalidated()) 8528 continue; 8529 switch (N.getOpcode()) { 8530 default: 8531 break; 8532 case ISD::ADD: 8533 SDValue N0 = N.getOperand(0); 8534 SDValue N1 = N.getOperand(1); 8535 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8536 isConstantIntBuildVectorOrConstantInt(N1)) { 8537 uint64_t Offset = N.getConstantOperandVal(1); 8538 // Rewrite an ADD constant node into a DIExpression. Since we are 8539 // performing arithmetic to compute the variable's *value* in the 8540 // DIExpression, we need to mark the expression with a 8541 // DW_OP_stack_value. 8542 auto *DIExpr = DV->getExpression(); 8543 DIExpr = 8544 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset); 8545 SDDbgValue *Clone = 8546 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(), 8547 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder()); 8548 ClonedDVs.push_back(Clone); 8549 DV->setIsInvalidated(); 8550 DV->setIsEmitted(); 8551 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8552 N0.getNode()->dumprFull(this); 8553 dbgs() << " into " << *DIExpr << '\n'); 8554 } 8555 } 8556 } 8557 8558 for (SDDbgValue *Dbg : ClonedDVs) 8559 AddDbgValue(Dbg, Dbg->getSDNode(), false); 8560 } 8561 8562 /// Creates a SDDbgLabel node. 8563 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8564 const DebugLoc &DL, unsigned O) { 8565 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8566 "Expected inlined-at fields to agree"); 8567 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8568 } 8569 8570 namespace { 8571 8572 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8573 /// pointed to by a use iterator is deleted, increment the use iterator 8574 /// so that it doesn't dangle. 8575 /// 8576 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8577 SDNode::use_iterator &UI; 8578 SDNode::use_iterator &UE; 8579 8580 void NodeDeleted(SDNode *N, SDNode *E) override { 8581 // Increment the iterator as needed. 8582 while (UI != UE && N == *UI) 8583 ++UI; 8584 } 8585 8586 public: 8587 RAUWUpdateListener(SelectionDAG &d, 8588 SDNode::use_iterator &ui, 8589 SDNode::use_iterator &ue) 8590 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8591 }; 8592 8593 } // end anonymous namespace 8594 8595 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8596 /// This can cause recursive merging of nodes in the DAG. 8597 /// 8598 /// This version assumes From has a single result value. 8599 /// 8600 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8601 SDNode *From = FromN.getNode(); 8602 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8603 "Cannot replace with this method!"); 8604 assert(From != To.getNode() && "Cannot replace uses of with self"); 8605 8606 // Preserve Debug Values 8607 transferDbgValues(FromN, To); 8608 8609 // Iterate over all the existing uses of From. New uses will be added 8610 // to the beginning of the use list, which we avoid visiting. 8611 // This specifically avoids visiting uses of From that arise while the 8612 // replacement is happening, because any such uses would be the result 8613 // of CSE: If an existing node looks like From after one of its operands 8614 // is replaced by To, we don't want to replace of all its users with To 8615 // too. See PR3018 for more info. 8616 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8617 RAUWUpdateListener Listener(*this, UI, UE); 8618 while (UI != UE) { 8619 SDNode *User = *UI; 8620 8621 // This node is about to morph, remove its old self from the CSE maps. 8622 RemoveNodeFromCSEMaps(User); 8623 8624 // A user can appear in a use list multiple times, and when this 8625 // happens the uses are usually next to each other in the list. 8626 // To help reduce the number of CSE recomputations, process all 8627 // the uses of this user that we can find this way. 8628 do { 8629 SDUse &Use = UI.getUse(); 8630 ++UI; 8631 Use.set(To); 8632 if (To->isDivergent() != From->isDivergent()) 8633 updateDivergence(User); 8634 } while (UI != UE && *UI == User); 8635 // Now that we have modified User, add it back to the CSE maps. If it 8636 // already exists there, recursively merge the results together. 8637 AddModifiedNodeToCSEMaps(User); 8638 } 8639 8640 // If we just RAUW'd the root, take note. 8641 if (FromN == getRoot()) 8642 setRoot(To); 8643 } 8644 8645 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8646 /// This can cause recursive merging of nodes in the DAG. 8647 /// 8648 /// This version assumes that for each value of From, there is a 8649 /// corresponding value in To in the same position with the same type. 8650 /// 8651 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8652 #ifndef NDEBUG 8653 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8654 assert((!From->hasAnyUseOfValue(i) || 8655 From->getValueType(i) == To->getValueType(i)) && 8656 "Cannot use this version of ReplaceAllUsesWith!"); 8657 #endif 8658 8659 // Handle the trivial case. 8660 if (From == To) 8661 return; 8662 8663 // Preserve Debug Info. Only do this if there's a use. 8664 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8665 if (From->hasAnyUseOfValue(i)) { 8666 assert((i < To->getNumValues()) && "Invalid To location"); 8667 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8668 } 8669 8670 // Iterate over just the existing users of From. See the comments in 8671 // the ReplaceAllUsesWith above. 8672 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8673 RAUWUpdateListener Listener(*this, UI, UE); 8674 while (UI != UE) { 8675 SDNode *User = *UI; 8676 8677 // This node is about to morph, remove its old self from the CSE maps. 8678 RemoveNodeFromCSEMaps(User); 8679 8680 // A user can appear in a use list multiple times, and when this 8681 // happens the uses are usually next to each other in the list. 8682 // To help reduce the number of CSE recomputations, process all 8683 // the uses of this user that we can find this way. 8684 do { 8685 SDUse &Use = UI.getUse(); 8686 ++UI; 8687 Use.setNode(To); 8688 if (To->isDivergent() != From->isDivergent()) 8689 updateDivergence(User); 8690 } while (UI != UE && *UI == User); 8691 8692 // Now that we have modified User, add it back to the CSE maps. If it 8693 // already exists there, recursively merge the results together. 8694 AddModifiedNodeToCSEMaps(User); 8695 } 8696 8697 // If we just RAUW'd the root, take note. 8698 if (From == getRoot().getNode()) 8699 setRoot(SDValue(To, getRoot().getResNo())); 8700 } 8701 8702 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8703 /// This can cause recursive merging of nodes in the DAG. 8704 /// 8705 /// This version can replace From with any result values. To must match the 8706 /// number and types of values returned by From. 8707 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8708 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8709 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8710 8711 // Preserve Debug Info. 8712 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8713 transferDbgValues(SDValue(From, i), To[i]); 8714 8715 // Iterate over just the existing users of From. See the comments in 8716 // the ReplaceAllUsesWith above. 8717 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8718 RAUWUpdateListener Listener(*this, UI, UE); 8719 while (UI != UE) { 8720 SDNode *User = *UI; 8721 8722 // This node is about to morph, remove its old self from the CSE maps. 8723 RemoveNodeFromCSEMaps(User); 8724 8725 // A user can appear in a use list multiple times, and when this happens the 8726 // uses are usually next to each other in the list. To help reduce the 8727 // number of CSE and divergence recomputations, process all the uses of this 8728 // user that we can find this way. 8729 bool To_IsDivergent = false; 8730 do { 8731 SDUse &Use = UI.getUse(); 8732 const SDValue &ToOp = To[Use.getResNo()]; 8733 ++UI; 8734 Use.set(ToOp); 8735 To_IsDivergent |= ToOp->isDivergent(); 8736 } while (UI != UE && *UI == User); 8737 8738 if (To_IsDivergent != From->isDivergent()) 8739 updateDivergence(User); 8740 8741 // Now that we have modified User, add it back to the CSE maps. If it 8742 // already exists there, recursively merge the results together. 8743 AddModifiedNodeToCSEMaps(User); 8744 } 8745 8746 // If we just RAUW'd the root, take note. 8747 if (From == getRoot().getNode()) 8748 setRoot(SDValue(To[getRoot().getResNo()])); 8749 } 8750 8751 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8752 /// uses of other values produced by From.getNode() alone. The Deleted 8753 /// vector is handled the same way as for ReplaceAllUsesWith. 8754 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8755 // Handle the really simple, really trivial case efficiently. 8756 if (From == To) return; 8757 8758 // Handle the simple, trivial, case efficiently. 8759 if (From.getNode()->getNumValues() == 1) { 8760 ReplaceAllUsesWith(From, To); 8761 return; 8762 } 8763 8764 // Preserve Debug Info. 8765 transferDbgValues(From, To); 8766 8767 // Iterate over just the existing users of From. See the comments in 8768 // the ReplaceAllUsesWith above. 8769 SDNode::use_iterator UI = From.getNode()->use_begin(), 8770 UE = From.getNode()->use_end(); 8771 RAUWUpdateListener Listener(*this, UI, UE); 8772 while (UI != UE) { 8773 SDNode *User = *UI; 8774 bool UserRemovedFromCSEMaps = false; 8775 8776 // A user can appear in a use list multiple times, and when this 8777 // happens the uses are usually next to each other in the list. 8778 // To help reduce the number of CSE recomputations, process all 8779 // the uses of this user that we can find this way. 8780 do { 8781 SDUse &Use = UI.getUse(); 8782 8783 // Skip uses of different values from the same node. 8784 if (Use.getResNo() != From.getResNo()) { 8785 ++UI; 8786 continue; 8787 } 8788 8789 // If this node hasn't been modified yet, it's still in the CSE maps, 8790 // so remove its old self from the CSE maps. 8791 if (!UserRemovedFromCSEMaps) { 8792 RemoveNodeFromCSEMaps(User); 8793 UserRemovedFromCSEMaps = true; 8794 } 8795 8796 ++UI; 8797 Use.set(To); 8798 if (To->isDivergent() != From->isDivergent()) 8799 updateDivergence(User); 8800 } while (UI != UE && *UI == User); 8801 // We are iterating over all uses of the From node, so if a use 8802 // doesn't use the specific value, no changes are made. 8803 if (!UserRemovedFromCSEMaps) 8804 continue; 8805 8806 // Now that we have modified User, add it back to the CSE maps. If it 8807 // already exists there, recursively merge the results together. 8808 AddModifiedNodeToCSEMaps(User); 8809 } 8810 8811 // If we just RAUW'd the root, take note. 8812 if (From == getRoot()) 8813 setRoot(To); 8814 } 8815 8816 namespace { 8817 8818 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 8819 /// to record information about a use. 8820 struct UseMemo { 8821 SDNode *User; 8822 unsigned Index; 8823 SDUse *Use; 8824 }; 8825 8826 /// operator< - Sort Memos by User. 8827 bool operator<(const UseMemo &L, const UseMemo &R) { 8828 return (intptr_t)L.User < (intptr_t)R.User; 8829 } 8830 8831 } // end anonymous namespace 8832 8833 bool SelectionDAG::calculateDivergence(SDNode *N) { 8834 if (TLI->isSDNodeAlwaysUniform(N)) { 8835 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 8836 "Conflicting divergence information!"); 8837 return false; 8838 } 8839 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 8840 return true; 8841 for (auto &Op : N->ops()) { 8842 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 8843 return true; 8844 } 8845 return false; 8846 } 8847 8848 void SelectionDAG::updateDivergence(SDNode *N) { 8849 SmallVector<SDNode *, 16> Worklist(1, N); 8850 do { 8851 N = Worklist.pop_back_val(); 8852 bool IsDivergent = calculateDivergence(N); 8853 if (N->SDNodeBits.IsDivergent != IsDivergent) { 8854 N->SDNodeBits.IsDivergent = IsDivergent; 8855 llvm::append_range(Worklist, N->uses()); 8856 } 8857 } while (!Worklist.empty()); 8858 } 8859 8860 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 8861 DenseMap<SDNode *, unsigned> Degree; 8862 Order.reserve(AllNodes.size()); 8863 for (auto &N : allnodes()) { 8864 unsigned NOps = N.getNumOperands(); 8865 Degree[&N] = NOps; 8866 if (0 == NOps) 8867 Order.push_back(&N); 8868 } 8869 for (size_t I = 0; I != Order.size(); ++I) { 8870 SDNode *N = Order[I]; 8871 for (auto U : N->uses()) { 8872 unsigned &UnsortedOps = Degree[U]; 8873 if (0 == --UnsortedOps) 8874 Order.push_back(U); 8875 } 8876 } 8877 } 8878 8879 #ifndef NDEBUG 8880 void SelectionDAG::VerifyDAGDiverence() { 8881 std::vector<SDNode *> TopoOrder; 8882 CreateTopologicalOrder(TopoOrder); 8883 for (auto *N : TopoOrder) { 8884 assert(calculateDivergence(N) == N->isDivergent() && 8885 "Divergence bit inconsistency detected"); 8886 } 8887 } 8888 #endif 8889 8890 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 8891 /// uses of other values produced by From.getNode() alone. The same value 8892 /// may appear in both the From and To list. The Deleted vector is 8893 /// handled the same way as for ReplaceAllUsesWith. 8894 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 8895 const SDValue *To, 8896 unsigned Num){ 8897 // Handle the simple, trivial case efficiently. 8898 if (Num == 1) 8899 return ReplaceAllUsesOfValueWith(*From, *To); 8900 8901 transferDbgValues(*From, *To); 8902 8903 // Read up all the uses and make records of them. This helps 8904 // processing new uses that are introduced during the 8905 // replacement process. 8906 SmallVector<UseMemo, 4> Uses; 8907 for (unsigned i = 0; i != Num; ++i) { 8908 unsigned FromResNo = From[i].getResNo(); 8909 SDNode *FromNode = From[i].getNode(); 8910 for (SDNode::use_iterator UI = FromNode->use_begin(), 8911 E = FromNode->use_end(); UI != E; ++UI) { 8912 SDUse &Use = UI.getUse(); 8913 if (Use.getResNo() == FromResNo) { 8914 UseMemo Memo = { *UI, i, &Use }; 8915 Uses.push_back(Memo); 8916 } 8917 } 8918 } 8919 8920 // Sort the uses, so that all the uses from a given User are together. 8921 llvm::sort(Uses); 8922 8923 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 8924 UseIndex != UseIndexEnd; ) { 8925 // We know that this user uses some value of From. If it is the right 8926 // value, update it. 8927 SDNode *User = Uses[UseIndex].User; 8928 8929 // This node is about to morph, remove its old self from the CSE maps. 8930 RemoveNodeFromCSEMaps(User); 8931 8932 // The Uses array is sorted, so all the uses for a given User 8933 // are next to each other in the list. 8934 // To help reduce the number of CSE recomputations, process all 8935 // the uses of this user that we can find this way. 8936 do { 8937 unsigned i = Uses[UseIndex].Index; 8938 SDUse &Use = *Uses[UseIndex].Use; 8939 ++UseIndex; 8940 8941 Use.set(To[i]); 8942 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 8943 8944 // Now that we have modified User, add it back to the CSE maps. If it 8945 // already exists there, recursively merge the results together. 8946 AddModifiedNodeToCSEMaps(User); 8947 } 8948 } 8949 8950 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 8951 /// based on their topological order. It returns the maximum id and a vector 8952 /// of the SDNodes* in assigned order by reference. 8953 unsigned SelectionDAG::AssignTopologicalOrder() { 8954 unsigned DAGSize = 0; 8955 8956 // SortedPos tracks the progress of the algorithm. Nodes before it are 8957 // sorted, nodes after it are unsorted. When the algorithm completes 8958 // it is at the end of the list. 8959 allnodes_iterator SortedPos = allnodes_begin(); 8960 8961 // Visit all the nodes. Move nodes with no operands to the front of 8962 // the list immediately. Annotate nodes that do have operands with their 8963 // operand count. Before we do this, the Node Id fields of the nodes 8964 // may contain arbitrary values. After, the Node Id fields for nodes 8965 // before SortedPos will contain the topological sort index, and the 8966 // Node Id fields for nodes At SortedPos and after will contain the 8967 // count of outstanding operands. 8968 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 8969 SDNode *N = &*I++; 8970 checkForCycles(N, this); 8971 unsigned Degree = N->getNumOperands(); 8972 if (Degree == 0) { 8973 // A node with no uses, add it to the result array immediately. 8974 N->setNodeId(DAGSize++); 8975 allnodes_iterator Q(N); 8976 if (Q != SortedPos) 8977 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 8978 assert(SortedPos != AllNodes.end() && "Overran node list"); 8979 ++SortedPos; 8980 } else { 8981 // Temporarily use the Node Id as scratch space for the degree count. 8982 N->setNodeId(Degree); 8983 } 8984 } 8985 8986 // Visit all the nodes. As we iterate, move nodes into sorted order, 8987 // such that by the time the end is reached all nodes will be sorted. 8988 for (SDNode &Node : allnodes()) { 8989 SDNode *N = &Node; 8990 checkForCycles(N, this); 8991 // N is in sorted position, so all its uses have one less operand 8992 // that needs to be sorted. 8993 for (SDNode *P : N->uses()) { 8994 unsigned Degree = P->getNodeId(); 8995 assert(Degree != 0 && "Invalid node degree"); 8996 --Degree; 8997 if (Degree == 0) { 8998 // All of P's operands are sorted, so P may sorted now. 8999 P->setNodeId(DAGSize++); 9000 if (P->getIterator() != SortedPos) 9001 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9002 assert(SortedPos != AllNodes.end() && "Overran node list"); 9003 ++SortedPos; 9004 } else { 9005 // Update P's outstanding operand count. 9006 P->setNodeId(Degree); 9007 } 9008 } 9009 if (Node.getIterator() == SortedPos) { 9010 #ifndef NDEBUG 9011 allnodes_iterator I(N); 9012 SDNode *S = &*++I; 9013 dbgs() << "Overran sorted position:\n"; 9014 S->dumprFull(this); dbgs() << "\n"; 9015 dbgs() << "Checking if this is due to cycles\n"; 9016 checkForCycles(this, true); 9017 #endif 9018 llvm_unreachable(nullptr); 9019 } 9020 } 9021 9022 assert(SortedPos == AllNodes.end() && 9023 "Topological sort incomplete!"); 9024 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9025 "First node in topological sort is not the entry token!"); 9026 assert(AllNodes.front().getNodeId() == 0 && 9027 "First node in topological sort has non-zero id!"); 9028 assert(AllNodes.front().getNumOperands() == 0 && 9029 "First node in topological sort has operands!"); 9030 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9031 "Last node in topologic sort has unexpected id!"); 9032 assert(AllNodes.back().use_empty() && 9033 "Last node in topologic sort has users!"); 9034 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9035 return DAGSize; 9036 } 9037 9038 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9039 /// value is produced by SD. 9040 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 9041 if (SD) { 9042 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9043 SD->setHasDebugValue(true); 9044 } 9045 DbgInfo->add(DB, SD, isParameter); 9046 } 9047 9048 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { 9049 DbgInfo->add(DB); 9050 } 9051 9052 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9053 SDValue NewMemOpChain) { 9054 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9055 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9056 // The new memory operation must have the same position as the old load in 9057 // terms of memory dependency. Create a TokenFactor for the old load and new 9058 // memory operation and update uses of the old load's output chain to use that 9059 // TokenFactor. 9060 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9061 return NewMemOpChain; 9062 9063 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9064 OldChain, NewMemOpChain); 9065 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9066 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9067 return TokenFactor; 9068 } 9069 9070 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9071 SDValue NewMemOp) { 9072 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9073 SDValue OldChain = SDValue(OldLoad, 1); 9074 SDValue NewMemOpChain = NewMemOp.getValue(1); 9075 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9076 } 9077 9078 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9079 Function **OutFunction) { 9080 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9081 9082 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9083 auto *Module = MF->getFunction().getParent(); 9084 auto *Function = Module->getFunction(Symbol); 9085 9086 if (OutFunction != nullptr) 9087 *OutFunction = Function; 9088 9089 if (Function != nullptr) { 9090 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9091 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9092 } 9093 9094 std::string ErrorStr; 9095 raw_string_ostream ErrorFormatter(ErrorStr); 9096 9097 ErrorFormatter << "Undefined external symbol "; 9098 ErrorFormatter << '"' << Symbol << '"'; 9099 ErrorFormatter.flush(); 9100 9101 report_fatal_error(ErrorStr); 9102 } 9103 9104 //===----------------------------------------------------------------------===// 9105 // SDNode Class 9106 //===----------------------------------------------------------------------===// 9107 9108 bool llvm::isNullConstant(SDValue V) { 9109 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9110 return Const != nullptr && Const->isNullValue(); 9111 } 9112 9113 bool llvm::isNullFPConstant(SDValue V) { 9114 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9115 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9116 } 9117 9118 bool llvm::isAllOnesConstant(SDValue V) { 9119 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9120 return Const != nullptr && Const->isAllOnesValue(); 9121 } 9122 9123 bool llvm::isOneConstant(SDValue V) { 9124 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9125 return Const != nullptr && Const->isOne(); 9126 } 9127 9128 SDValue llvm::peekThroughBitcasts(SDValue V) { 9129 while (V.getOpcode() == ISD::BITCAST) 9130 V = V.getOperand(0); 9131 return V; 9132 } 9133 9134 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9135 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9136 V = V.getOperand(0); 9137 return V; 9138 } 9139 9140 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9141 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9142 V = V.getOperand(0); 9143 return V; 9144 } 9145 9146 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9147 if (V.getOpcode() != ISD::XOR) 9148 return false; 9149 V = peekThroughBitcasts(V.getOperand(1)); 9150 unsigned NumBits = V.getScalarValueSizeInBits(); 9151 ConstantSDNode *C = 9152 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9153 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9154 } 9155 9156 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9157 bool AllowTruncation) { 9158 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9159 return CN; 9160 9161 // SplatVectors can truncate their operands. Ignore that case here unless 9162 // AllowTruncation is set. 9163 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9164 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9165 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9166 EVT CVT = CN->getValueType(0); 9167 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9168 if (AllowTruncation || CVT == VecEltVT) 9169 return CN; 9170 } 9171 } 9172 9173 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9174 BitVector UndefElements; 9175 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9176 9177 // BuildVectors can truncate their operands. Ignore that case here unless 9178 // AllowTruncation is set. 9179 if (CN && (UndefElements.none() || AllowUndefs)) { 9180 EVT CVT = CN->getValueType(0); 9181 EVT NSVT = N.getValueType().getScalarType(); 9182 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9183 if (AllowTruncation || (CVT == NSVT)) 9184 return CN; 9185 } 9186 } 9187 9188 return nullptr; 9189 } 9190 9191 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9192 bool AllowUndefs, 9193 bool AllowTruncation) { 9194 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9195 return CN; 9196 9197 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9198 BitVector UndefElements; 9199 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9200 9201 // BuildVectors can truncate their operands. Ignore that case here unless 9202 // AllowTruncation is set. 9203 if (CN && (UndefElements.none() || AllowUndefs)) { 9204 EVT CVT = CN->getValueType(0); 9205 EVT NSVT = N.getValueType().getScalarType(); 9206 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9207 if (AllowTruncation || (CVT == NSVT)) 9208 return CN; 9209 } 9210 } 9211 9212 return nullptr; 9213 } 9214 9215 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9216 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9217 return CN; 9218 9219 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9220 BitVector UndefElements; 9221 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9222 if (CN && (UndefElements.none() || AllowUndefs)) 9223 return CN; 9224 } 9225 9226 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9227 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9228 return CN; 9229 9230 return nullptr; 9231 } 9232 9233 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9234 const APInt &DemandedElts, 9235 bool AllowUndefs) { 9236 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9237 return CN; 9238 9239 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9240 BitVector UndefElements; 9241 ConstantFPSDNode *CN = 9242 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9243 if (CN && (UndefElements.none() || AllowUndefs)) 9244 return CN; 9245 } 9246 9247 return nullptr; 9248 } 9249 9250 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9251 // TODO: may want to use peekThroughBitcast() here. 9252 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9253 return C && C->isNullValue(); 9254 } 9255 9256 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9257 // TODO: may want to use peekThroughBitcast() here. 9258 unsigned BitWidth = N.getScalarValueSizeInBits(); 9259 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9260 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9261 } 9262 9263 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9264 N = peekThroughBitcasts(N); 9265 unsigned BitWidth = N.getScalarValueSizeInBits(); 9266 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9267 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9268 } 9269 9270 HandleSDNode::~HandleSDNode() { 9271 DropOperands(); 9272 } 9273 9274 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9275 const DebugLoc &DL, 9276 const GlobalValue *GA, EVT VT, 9277 int64_t o, unsigned TF) 9278 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9279 TheGlobal = GA; 9280 } 9281 9282 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9283 EVT VT, unsigned SrcAS, 9284 unsigned DestAS) 9285 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9286 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9287 9288 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9289 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9290 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9291 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9292 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9293 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9294 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9295 9296 // We check here that the size of the memory operand fits within the size of 9297 // the MMO. This is because the MMO might indicate only a possible address 9298 // range instead of specifying the affected memory addresses precisely. 9299 // TODO: Make MachineMemOperands aware of scalable vectors. 9300 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9301 "Size mismatch!"); 9302 } 9303 9304 /// Profile - Gather unique data for the node. 9305 /// 9306 void SDNode::Profile(FoldingSetNodeID &ID) const { 9307 AddNodeIDNode(ID, this); 9308 } 9309 9310 namespace { 9311 9312 struct EVTArray { 9313 std::vector<EVT> VTs; 9314 9315 EVTArray() { 9316 VTs.reserve(MVT::LAST_VALUETYPE); 9317 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9318 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9319 } 9320 }; 9321 9322 } // end anonymous namespace 9323 9324 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9325 static ManagedStatic<EVTArray> SimpleVTArray; 9326 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9327 9328 /// getValueTypeList - Return a pointer to the specified value type. 9329 /// 9330 const EVT *SDNode::getValueTypeList(EVT VT) { 9331 if (VT.isExtended()) { 9332 sys::SmartScopedLock<true> Lock(*VTMutex); 9333 return &(*EVTs->insert(VT).first); 9334 } else { 9335 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 9336 "Value type out of range!"); 9337 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9338 } 9339 } 9340 9341 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9342 /// indicated value. This method ignores uses of other values defined by this 9343 /// operation. 9344 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9345 assert(Value < getNumValues() && "Bad value!"); 9346 9347 // TODO: Only iterate over uses of a given value of the node 9348 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9349 if (UI.getUse().getResNo() == Value) { 9350 if (NUses == 0) 9351 return false; 9352 --NUses; 9353 } 9354 } 9355 9356 // Found exactly the right number of uses? 9357 return NUses == 0; 9358 } 9359 9360 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9361 /// value. This method ignores uses of other values defined by this operation. 9362 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9363 assert(Value < getNumValues() && "Bad value!"); 9364 9365 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9366 if (UI.getUse().getResNo() == Value) 9367 return true; 9368 9369 return false; 9370 } 9371 9372 /// isOnlyUserOf - Return true if this node is the only use of N. 9373 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9374 bool Seen = false; 9375 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9376 SDNode *User = *I; 9377 if (User == this) 9378 Seen = true; 9379 else 9380 return false; 9381 } 9382 9383 return Seen; 9384 } 9385 9386 /// Return true if the only users of N are contained in Nodes. 9387 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9388 bool Seen = false; 9389 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9390 SDNode *User = *I; 9391 if (llvm::is_contained(Nodes, User)) 9392 Seen = true; 9393 else 9394 return false; 9395 } 9396 9397 return Seen; 9398 } 9399 9400 /// isOperand - Return true if this node is an operand of N. 9401 bool SDValue::isOperandOf(const SDNode *N) const { 9402 return is_contained(N->op_values(), *this); 9403 } 9404 9405 bool SDNode::isOperandOf(const SDNode *N) const { 9406 return any_of(N->op_values(), 9407 [this](SDValue Op) { return this == Op.getNode(); }); 9408 } 9409 9410 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9411 /// be a chain) reaches the specified operand without crossing any 9412 /// side-effecting instructions on any chain path. In practice, this looks 9413 /// through token factors and non-volatile loads. In order to remain efficient, 9414 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9415 /// 9416 /// Note that we only need to examine chains when we're searching for 9417 /// side-effects; SelectionDAG requires that all side-effects are represented 9418 /// by chains, even if another operand would force a specific ordering. This 9419 /// constraint is necessary to allow transformations like splitting loads. 9420 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9421 unsigned Depth) const { 9422 if (*this == Dest) return true; 9423 9424 // Don't search too deeply, we just want to be able to see through 9425 // TokenFactor's etc. 9426 if (Depth == 0) return false; 9427 9428 // If this is a token factor, all inputs to the TF happen in parallel. 9429 if (getOpcode() == ISD::TokenFactor) { 9430 // First, try a shallow search. 9431 if (is_contained((*this)->ops(), Dest)) { 9432 // We found the chain we want as an operand of this TokenFactor. 9433 // Essentially, we reach the chain without side-effects if we could 9434 // serialize the TokenFactor into a simple chain of operations with 9435 // Dest as the last operation. This is automatically true if the 9436 // chain has one use: there are no other ordering constraints. 9437 // If the chain has more than one use, we give up: some other 9438 // use of Dest might force a side-effect between Dest and the current 9439 // node. 9440 if (Dest.hasOneUse()) 9441 return true; 9442 } 9443 // Next, try a deep search: check whether every operand of the TokenFactor 9444 // reaches Dest. 9445 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9446 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9447 }); 9448 } 9449 9450 // Loads don't have side effects, look through them. 9451 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9452 if (Ld->isUnordered()) 9453 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9454 } 9455 return false; 9456 } 9457 9458 bool SDNode::hasPredecessor(const SDNode *N) const { 9459 SmallPtrSet<const SDNode *, 32> Visited; 9460 SmallVector<const SDNode *, 16> Worklist; 9461 Worklist.push_back(this); 9462 return hasPredecessorHelper(N, Visited, Worklist); 9463 } 9464 9465 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9466 this->Flags.intersectWith(Flags); 9467 } 9468 9469 SDValue 9470 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9471 ArrayRef<ISD::NodeType> CandidateBinOps, 9472 bool AllowPartials) { 9473 // The pattern must end in an extract from index 0. 9474 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9475 !isNullConstant(Extract->getOperand(1))) 9476 return SDValue(); 9477 9478 // Match against one of the candidate binary ops. 9479 SDValue Op = Extract->getOperand(0); 9480 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9481 return Op.getOpcode() == unsigned(BinOp); 9482 })) 9483 return SDValue(); 9484 9485 // Floating-point reductions may require relaxed constraints on the final step 9486 // of the reduction because they may reorder intermediate operations. 9487 unsigned CandidateBinOp = Op.getOpcode(); 9488 if (Op.getValueType().isFloatingPoint()) { 9489 SDNodeFlags Flags = Op->getFlags(); 9490 switch (CandidateBinOp) { 9491 case ISD::FADD: 9492 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9493 return SDValue(); 9494 break; 9495 default: 9496 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9497 } 9498 } 9499 9500 // Matching failed - attempt to see if we did enough stages that a partial 9501 // reduction from a subvector is possible. 9502 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9503 if (!AllowPartials || !Op) 9504 return SDValue(); 9505 EVT OpVT = Op.getValueType(); 9506 EVT OpSVT = OpVT.getScalarType(); 9507 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9508 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9509 return SDValue(); 9510 BinOp = (ISD::NodeType)CandidateBinOp; 9511 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9512 getVectorIdxConstant(0, SDLoc(Op))); 9513 }; 9514 9515 // At each stage, we're looking for something that looks like: 9516 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9517 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9518 // i32 undef, i32 undef, i32 undef, i32 undef> 9519 // %a = binop <8 x i32> %op, %s 9520 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9521 // we expect something like: 9522 // <4,5,6,7,u,u,u,u> 9523 // <2,3,u,u,u,u,u,u> 9524 // <1,u,u,u,u,u,u,u> 9525 // While a partial reduction match would be: 9526 // <2,3,u,u,u,u,u,u> 9527 // <1,u,u,u,u,u,u,u> 9528 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9529 SDValue PrevOp; 9530 for (unsigned i = 0; i < Stages; ++i) { 9531 unsigned MaskEnd = (1 << i); 9532 9533 if (Op.getOpcode() != CandidateBinOp) 9534 return PartialReduction(PrevOp, MaskEnd); 9535 9536 SDValue Op0 = Op.getOperand(0); 9537 SDValue Op1 = Op.getOperand(1); 9538 9539 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9540 if (Shuffle) { 9541 Op = Op1; 9542 } else { 9543 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9544 Op = Op0; 9545 } 9546 9547 // The first operand of the shuffle should be the same as the other operand 9548 // of the binop. 9549 if (!Shuffle || Shuffle->getOperand(0) != Op) 9550 return PartialReduction(PrevOp, MaskEnd); 9551 9552 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9553 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9554 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9555 return PartialReduction(PrevOp, MaskEnd); 9556 9557 PrevOp = Op; 9558 } 9559 9560 // Handle subvector reductions, which tend to appear after the shuffle 9561 // reduction stages. 9562 while (Op.getOpcode() == CandidateBinOp) { 9563 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9564 SDValue Op0 = Op.getOperand(0); 9565 SDValue Op1 = Op.getOperand(1); 9566 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9567 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9568 Op0.getOperand(0) != Op1.getOperand(0)) 9569 break; 9570 SDValue Src = Op0.getOperand(0); 9571 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9572 if (NumSrcElts != (2 * NumElts)) 9573 break; 9574 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9575 Op1.getConstantOperandAPInt(1) == NumElts) && 9576 !(Op1.getConstantOperandAPInt(1) == 0 && 9577 Op0.getConstantOperandAPInt(1) == NumElts)) 9578 break; 9579 Op = Src; 9580 } 9581 9582 BinOp = (ISD::NodeType)CandidateBinOp; 9583 return Op; 9584 } 9585 9586 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9587 assert(N->getNumValues() == 1 && 9588 "Can't unroll a vector with multiple results!"); 9589 9590 EVT VT = N->getValueType(0); 9591 unsigned NE = VT.getVectorNumElements(); 9592 EVT EltVT = VT.getVectorElementType(); 9593 SDLoc dl(N); 9594 9595 SmallVector<SDValue, 8> Scalars; 9596 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9597 9598 // If ResNE is 0, fully unroll the vector op. 9599 if (ResNE == 0) 9600 ResNE = NE; 9601 else if (NE > ResNE) 9602 NE = ResNE; 9603 9604 unsigned i; 9605 for (i= 0; i != NE; ++i) { 9606 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9607 SDValue Operand = N->getOperand(j); 9608 EVT OperandVT = Operand.getValueType(); 9609 if (OperandVT.isVector()) { 9610 // A vector operand; extract a single element. 9611 EVT OperandEltVT = OperandVT.getVectorElementType(); 9612 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9613 Operand, getVectorIdxConstant(i, dl)); 9614 } else { 9615 // A scalar operand; just use it as is. 9616 Operands[j] = Operand; 9617 } 9618 } 9619 9620 switch (N->getOpcode()) { 9621 default: { 9622 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9623 N->getFlags())); 9624 break; 9625 } 9626 case ISD::VSELECT: 9627 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9628 break; 9629 case ISD::SHL: 9630 case ISD::SRA: 9631 case ISD::SRL: 9632 case ISD::ROTL: 9633 case ISD::ROTR: 9634 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9635 getShiftAmountOperand(Operands[0].getValueType(), 9636 Operands[1]))); 9637 break; 9638 case ISD::SIGN_EXTEND_INREG: { 9639 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9640 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9641 Operands[0], 9642 getValueType(ExtVT))); 9643 } 9644 } 9645 } 9646 9647 for (; i < ResNE; ++i) 9648 Scalars.push_back(getUNDEF(EltVT)); 9649 9650 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9651 return getBuildVector(VecVT, dl, Scalars); 9652 } 9653 9654 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9655 SDNode *N, unsigned ResNE) { 9656 unsigned Opcode = N->getOpcode(); 9657 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9658 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9659 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9660 "Expected an overflow opcode"); 9661 9662 EVT ResVT = N->getValueType(0); 9663 EVT OvVT = N->getValueType(1); 9664 EVT ResEltVT = ResVT.getVectorElementType(); 9665 EVT OvEltVT = OvVT.getVectorElementType(); 9666 SDLoc dl(N); 9667 9668 // If ResNE is 0, fully unroll the vector op. 9669 unsigned NE = ResVT.getVectorNumElements(); 9670 if (ResNE == 0) 9671 ResNE = NE; 9672 else if (NE > ResNE) 9673 NE = ResNE; 9674 9675 SmallVector<SDValue, 8> LHSScalars; 9676 SmallVector<SDValue, 8> RHSScalars; 9677 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9678 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9679 9680 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9681 SDVTList VTs = getVTList(ResEltVT, SVT); 9682 SmallVector<SDValue, 8> ResScalars; 9683 SmallVector<SDValue, 8> OvScalars; 9684 for (unsigned i = 0; i < NE; ++i) { 9685 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9686 SDValue Ov = 9687 getSelect(dl, OvEltVT, Res.getValue(1), 9688 getBoolConstant(true, dl, OvEltVT, ResVT), 9689 getConstant(0, dl, OvEltVT)); 9690 9691 ResScalars.push_back(Res); 9692 OvScalars.push_back(Ov); 9693 } 9694 9695 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9696 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9697 9698 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9699 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9700 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9701 getBuildVector(NewOvVT, dl, OvScalars)); 9702 } 9703 9704 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9705 LoadSDNode *Base, 9706 unsigned Bytes, 9707 int Dist) const { 9708 if (LD->isVolatile() || Base->isVolatile()) 9709 return false; 9710 // TODO: probably too restrictive for atomics, revisit 9711 if (!LD->isSimple()) 9712 return false; 9713 if (LD->isIndexed() || Base->isIndexed()) 9714 return false; 9715 if (LD->getChain() != Base->getChain()) 9716 return false; 9717 EVT VT = LD->getValueType(0); 9718 if (VT.getSizeInBits() / 8 != Bytes) 9719 return false; 9720 9721 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9722 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9723 9724 int64_t Offset = 0; 9725 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9726 return (Dist * Bytes == Offset); 9727 return false; 9728 } 9729 9730 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 9731 /// if it cannot be inferred. 9732 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 9733 // If this is a GlobalAddress + cst, return the alignment. 9734 const GlobalValue *GV = nullptr; 9735 int64_t GVOffset = 0; 9736 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9737 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 9738 KnownBits Known(PtrWidth); 9739 llvm::computeKnownBits(GV, Known, getDataLayout()); 9740 unsigned AlignBits = Known.countMinTrailingZeros(); 9741 if (AlignBits) 9742 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 9743 } 9744 9745 // If this is a direct reference to a stack slot, use information about the 9746 // stack slot's alignment. 9747 int FrameIdx = INT_MIN; 9748 int64_t FrameOffset = 0; 9749 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9750 FrameIdx = FI->getIndex(); 9751 } else if (isBaseWithConstantOffset(Ptr) && 9752 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9753 // Handle FI+Cst 9754 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9755 FrameOffset = Ptr.getConstantOperandVal(1); 9756 } 9757 9758 if (FrameIdx != INT_MIN) { 9759 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9760 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 9761 } 9762 9763 return None; 9764 } 9765 9766 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9767 /// which is split (or expanded) into two not necessarily identical pieces. 9768 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9769 // Currently all types are split in half. 9770 EVT LoVT, HiVT; 9771 if (!VT.isVector()) 9772 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9773 else 9774 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9775 9776 return std::make_pair(LoVT, HiVT); 9777 } 9778 9779 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 9780 /// type, dependent on an enveloping VT that has been split into two identical 9781 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 9782 std::pair<EVT, EVT> 9783 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 9784 bool *HiIsEmpty) const { 9785 EVT EltTp = VT.getVectorElementType(); 9786 // Examples: 9787 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 9788 // custom VL=9 with enveloping VL=8/8 yields 8/1 9789 // custom VL=10 with enveloping VL=8/8 yields 8/2 9790 // etc. 9791 ElementCount VTNumElts = VT.getVectorElementCount(); 9792 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 9793 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 9794 "Mixing fixed width and scalable vectors when enveloping a type"); 9795 EVT LoVT, HiVT; 9796 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 9797 LoVT = EnvVT; 9798 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 9799 *HiIsEmpty = false; 9800 } else { 9801 // Flag that hi type has zero storage size, but return split envelop type 9802 // (this would be easier if vector types with zero elements were allowed). 9803 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 9804 HiVT = EnvVT; 9805 *HiIsEmpty = true; 9806 } 9807 return std::make_pair(LoVT, HiVT); 9808 } 9809 9810 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 9811 /// low/high part. 9812 std::pair<SDValue, SDValue> 9813 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 9814 const EVT &HiVT) { 9815 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 9816 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 9817 "Splitting vector with an invalid mixture of fixed and scalable " 9818 "vector types"); 9819 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 9820 N.getValueType().getVectorMinNumElements() && 9821 "More vector elements requested than available!"); 9822 SDValue Lo, Hi; 9823 Lo = 9824 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 9825 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 9826 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 9827 // IDX with the runtime scaling factor of the result vector type. For 9828 // fixed-width result vectors, that runtime scaling factor is 1. 9829 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 9830 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 9831 return std::make_pair(Lo, Hi); 9832 } 9833 9834 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 9835 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 9836 EVT VT = N.getValueType(); 9837 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 9838 NextPowerOf2(VT.getVectorNumElements())); 9839 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 9840 getVectorIdxConstant(0, DL)); 9841 } 9842 9843 void SelectionDAG::ExtractVectorElements(SDValue Op, 9844 SmallVectorImpl<SDValue> &Args, 9845 unsigned Start, unsigned Count, 9846 EVT EltVT) { 9847 EVT VT = Op.getValueType(); 9848 if (Count == 0) 9849 Count = VT.getVectorNumElements(); 9850 if (EltVT == EVT()) 9851 EltVT = VT.getVectorElementType(); 9852 SDLoc SL(Op); 9853 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 9854 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 9855 getVectorIdxConstant(i, SL))); 9856 } 9857 } 9858 9859 // getAddressSpace - Return the address space this GlobalAddress belongs to. 9860 unsigned GlobalAddressSDNode::getAddressSpace() const { 9861 return getGlobal()->getType()->getAddressSpace(); 9862 } 9863 9864 Type *ConstantPoolSDNode::getType() const { 9865 if (isMachineConstantPoolEntry()) 9866 return Val.MachineCPVal->getType(); 9867 return Val.ConstVal->getType(); 9868 } 9869 9870 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 9871 unsigned &SplatBitSize, 9872 bool &HasAnyUndefs, 9873 unsigned MinSplatBits, 9874 bool IsBigEndian) const { 9875 EVT VT = getValueType(0); 9876 assert(VT.isVector() && "Expected a vector type"); 9877 unsigned VecWidth = VT.getSizeInBits(); 9878 if (MinSplatBits > VecWidth) 9879 return false; 9880 9881 // FIXME: The widths are based on this node's type, but build vectors can 9882 // truncate their operands. 9883 SplatValue = APInt(VecWidth, 0); 9884 SplatUndef = APInt(VecWidth, 0); 9885 9886 // Get the bits. Bits with undefined values (when the corresponding element 9887 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 9888 // in SplatValue. If any of the values are not constant, give up and return 9889 // false. 9890 unsigned int NumOps = getNumOperands(); 9891 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 9892 unsigned EltWidth = VT.getScalarSizeInBits(); 9893 9894 for (unsigned j = 0; j < NumOps; ++j) { 9895 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 9896 SDValue OpVal = getOperand(i); 9897 unsigned BitPos = j * EltWidth; 9898 9899 if (OpVal.isUndef()) 9900 SplatUndef.setBits(BitPos, BitPos + EltWidth); 9901 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 9902 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 9903 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 9904 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 9905 else 9906 return false; 9907 } 9908 9909 // The build_vector is all constants or undefs. Find the smallest element 9910 // size that splats the vector. 9911 HasAnyUndefs = (SplatUndef != 0); 9912 9913 // FIXME: This does not work for vectors with elements less than 8 bits. 9914 while (VecWidth > 8) { 9915 unsigned HalfSize = VecWidth / 2; 9916 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 9917 APInt LowValue = SplatValue.trunc(HalfSize); 9918 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 9919 APInt LowUndef = SplatUndef.trunc(HalfSize); 9920 9921 // If the two halves do not match (ignoring undef bits), stop here. 9922 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 9923 MinSplatBits > HalfSize) 9924 break; 9925 9926 SplatValue = HighValue | LowValue; 9927 SplatUndef = HighUndef & LowUndef; 9928 9929 VecWidth = HalfSize; 9930 } 9931 9932 SplatBitSize = VecWidth; 9933 return true; 9934 } 9935 9936 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 9937 BitVector *UndefElements) const { 9938 unsigned NumOps = getNumOperands(); 9939 if (UndefElements) { 9940 UndefElements->clear(); 9941 UndefElements->resize(NumOps); 9942 } 9943 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 9944 if (!DemandedElts) 9945 return SDValue(); 9946 SDValue Splatted; 9947 for (unsigned i = 0; i != NumOps; ++i) { 9948 if (!DemandedElts[i]) 9949 continue; 9950 SDValue Op = getOperand(i); 9951 if (Op.isUndef()) { 9952 if (UndefElements) 9953 (*UndefElements)[i] = true; 9954 } else if (!Splatted) { 9955 Splatted = Op; 9956 } else if (Splatted != Op) { 9957 return SDValue(); 9958 } 9959 } 9960 9961 if (!Splatted) { 9962 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 9963 assert(getOperand(FirstDemandedIdx).isUndef() && 9964 "Can only have a splat without a constant for all undefs."); 9965 return getOperand(FirstDemandedIdx); 9966 } 9967 9968 return Splatted; 9969 } 9970 9971 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 9972 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 9973 return getSplatValue(DemandedElts, UndefElements); 9974 } 9975 9976 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 9977 SmallVectorImpl<SDValue> &Sequence, 9978 BitVector *UndefElements) const { 9979 unsigned NumOps = getNumOperands(); 9980 Sequence.clear(); 9981 if (UndefElements) { 9982 UndefElements->clear(); 9983 UndefElements->resize(NumOps); 9984 } 9985 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 9986 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 9987 return false; 9988 9989 // Set the undefs even if we don't find a sequence (like getSplatValue). 9990 if (UndefElements) 9991 for (unsigned I = 0; I != NumOps; ++I) 9992 if (DemandedElts[I] && getOperand(I).isUndef()) 9993 (*UndefElements)[I] = true; 9994 9995 // Iteratively widen the sequence length looking for repetitions. 9996 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 9997 Sequence.append(SeqLen, SDValue()); 9998 for (unsigned I = 0; I != NumOps; ++I) { 9999 if (!DemandedElts[I]) 10000 continue; 10001 SDValue &SeqOp = Sequence[I % SeqLen]; 10002 SDValue Op = getOperand(I); 10003 if (Op.isUndef()) { 10004 if (!SeqOp) 10005 SeqOp = Op; 10006 continue; 10007 } 10008 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10009 Sequence.clear(); 10010 break; 10011 } 10012 SeqOp = Op; 10013 } 10014 if (!Sequence.empty()) 10015 return true; 10016 } 10017 10018 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10019 return false; 10020 } 10021 10022 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10023 BitVector *UndefElements) const { 10024 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10025 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10026 } 10027 10028 ConstantSDNode * 10029 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10030 BitVector *UndefElements) const { 10031 return dyn_cast_or_null<ConstantSDNode>( 10032 getSplatValue(DemandedElts, UndefElements)); 10033 } 10034 10035 ConstantSDNode * 10036 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10037 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10038 } 10039 10040 ConstantFPSDNode * 10041 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10042 BitVector *UndefElements) const { 10043 return dyn_cast_or_null<ConstantFPSDNode>( 10044 getSplatValue(DemandedElts, UndefElements)); 10045 } 10046 10047 ConstantFPSDNode * 10048 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10049 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10050 } 10051 10052 int32_t 10053 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10054 uint32_t BitWidth) const { 10055 if (ConstantFPSDNode *CN = 10056 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10057 bool IsExact; 10058 APSInt IntVal(BitWidth); 10059 const APFloat &APF = CN->getValueAPF(); 10060 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10061 APFloat::opOK || 10062 !IsExact) 10063 return -1; 10064 10065 return IntVal.exactLogBase2(); 10066 } 10067 return -1; 10068 } 10069 10070 bool BuildVectorSDNode::isConstant() const { 10071 for (const SDValue &Op : op_values()) { 10072 unsigned Opc = Op.getOpcode(); 10073 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10074 return false; 10075 } 10076 return true; 10077 } 10078 10079 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10080 // Find the first non-undef value in the shuffle mask. 10081 unsigned i, e; 10082 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10083 /* search */; 10084 10085 // If all elements are undefined, this shuffle can be considered a splat 10086 // (although it should eventually get simplified away completely). 10087 if (i == e) 10088 return true; 10089 10090 // Make sure all remaining elements are either undef or the same as the first 10091 // non-undef value. 10092 for (int Idx = Mask[i]; i != e; ++i) 10093 if (Mask[i] >= 0 && Mask[i] != Idx) 10094 return false; 10095 return true; 10096 } 10097 10098 // Returns the SDNode if it is a constant integer BuildVector 10099 // or constant integer. 10100 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10101 if (isa<ConstantSDNode>(N)) 10102 return N.getNode(); 10103 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10104 return N.getNode(); 10105 // Treat a GlobalAddress supporting constant offset folding as a 10106 // constant integer. 10107 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10108 if (GA->getOpcode() == ISD::GlobalAddress && 10109 TLI->isOffsetFoldingLegal(GA)) 10110 return GA; 10111 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10112 isa<ConstantSDNode>(N.getOperand(0))) 10113 return N.getNode(); 10114 return nullptr; 10115 } 10116 10117 // Returns the SDNode if it is a constant float BuildVector 10118 // or constant float. 10119 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10120 if (isa<ConstantFPSDNode>(N)) 10121 return N.getNode(); 10122 10123 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10124 return N.getNode(); 10125 10126 return nullptr; 10127 } 10128 10129 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10130 assert(!Node->OperandList && "Node already has operands"); 10131 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10132 "too many operands to fit into SDNode"); 10133 SDUse *Ops = OperandRecycler.allocate( 10134 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10135 10136 bool IsDivergent = false; 10137 for (unsigned I = 0; I != Vals.size(); ++I) { 10138 Ops[I].setUser(Node); 10139 Ops[I].setInitial(Vals[I]); 10140 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10141 IsDivergent |= Ops[I].getNode()->isDivergent(); 10142 } 10143 Node->NumOperands = Vals.size(); 10144 Node->OperandList = Ops; 10145 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10146 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10147 Node->SDNodeBits.IsDivergent = IsDivergent; 10148 } 10149 checkForCycles(Node); 10150 } 10151 10152 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10153 SmallVectorImpl<SDValue> &Vals) { 10154 size_t Limit = SDNode::getMaxNumOperands(); 10155 while (Vals.size() > Limit) { 10156 unsigned SliceIdx = Vals.size() - Limit; 10157 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10158 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10159 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10160 Vals.emplace_back(NewTF); 10161 } 10162 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10163 } 10164 10165 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10166 EVT VT, SDNodeFlags Flags) { 10167 switch (Opcode) { 10168 default: 10169 return SDValue(); 10170 case ISD::ADD: 10171 case ISD::OR: 10172 case ISD::XOR: 10173 case ISD::UMAX: 10174 return getConstant(0, DL, VT); 10175 case ISD::MUL: 10176 return getConstant(1, DL, VT); 10177 case ISD::AND: 10178 case ISD::UMIN: 10179 return getAllOnesConstant(DL, VT); 10180 case ISD::SMAX: 10181 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10182 case ISD::SMIN: 10183 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10184 case ISD::FADD: 10185 return getConstantFP(-0.0, DL, VT); 10186 case ISD::FMUL: 10187 return getConstantFP(1.0, DL, VT); 10188 case ISD::FMINNUM: 10189 case ISD::FMAXNUM: { 10190 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10191 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10192 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10193 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10194 APFloat::getLargest(Semantics); 10195 if (Opcode == ISD::FMAXNUM) 10196 NeutralAF.changeSign(); 10197 10198 return getConstantFP(NeutralAF, DL, VT); 10199 } 10200 } 10201 } 10202 10203 #ifndef NDEBUG 10204 static void checkForCyclesHelper(const SDNode *N, 10205 SmallPtrSetImpl<const SDNode*> &Visited, 10206 SmallPtrSetImpl<const SDNode*> &Checked, 10207 const llvm::SelectionDAG *DAG) { 10208 // If this node has already been checked, don't check it again. 10209 if (Checked.count(N)) 10210 return; 10211 10212 // If a node has already been visited on this depth-first walk, reject it as 10213 // a cycle. 10214 if (!Visited.insert(N).second) { 10215 errs() << "Detected cycle in SelectionDAG\n"; 10216 dbgs() << "Offending node:\n"; 10217 N->dumprFull(DAG); dbgs() << "\n"; 10218 abort(); 10219 } 10220 10221 for (const SDValue &Op : N->op_values()) 10222 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10223 10224 Checked.insert(N); 10225 Visited.erase(N); 10226 } 10227 #endif 10228 10229 void llvm::checkForCycles(const llvm::SDNode *N, 10230 const llvm::SelectionDAG *DAG, 10231 bool force) { 10232 #ifndef NDEBUG 10233 bool check = force; 10234 #ifdef EXPENSIVE_CHECKS 10235 check = true; 10236 #endif // EXPENSIVE_CHECKS 10237 if (check) { 10238 assert(N && "Checking nonexistent SDNode"); 10239 SmallPtrSet<const SDNode*, 32> visited; 10240 SmallPtrSet<const SDNode*, 32> checked; 10241 checkForCyclesHelper(N, visited, checked, DAG); 10242 } 10243 #endif // !NDEBUG 10244 } 10245 10246 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10247 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10248 } 10249