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