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