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