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