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