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