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