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