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