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