1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/TargetLowering.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/CodeGen/CallingConvLower.h" 16 #include "llvm/CodeGen/MachineFrameInfo.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineJumpTableInfo.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/CodeGen/TargetRegisterInfo.h" 22 #include "llvm/CodeGen/TargetSubtargetInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/KnownBits.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Target/TargetLoweringObjectFile.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include <cctype> 35 using namespace llvm; 36 37 /// NOTE: The TargetMachine owns TLOF. 38 TargetLowering::TargetLowering(const TargetMachine &tm) 39 : TargetLoweringBase(tm) {} 40 41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 42 return nullptr; 43 } 44 45 bool TargetLowering::isPositionIndependent() const { 46 return getTargetMachine().isPositionIndependent(); 47 } 48 49 /// Check whether a given call node is in tail position within its function. If 50 /// so, it sets Chain to the input chain of the tail call. 51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 52 SDValue &Chain) const { 53 const Function &F = DAG.getMachineFunction().getFunction(); 54 55 // First, check if tail calls have been disabled in this function. 56 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 57 return false; 58 59 // Conservatively require the attributes of the call to match those of 60 // the return. Ignore NoAlias and NonNull because they don't affect the 61 // call sequence. 62 AttributeList CallerAttrs = F.getAttributes(); 63 if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex) 64 .removeAttribute(Attribute::NoAlias) 65 .removeAttribute(Attribute::NonNull) 66 .hasAttributes()) 67 return false; 68 69 // It's not safe to eliminate the sign / zero extension of the return value. 70 if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) || 71 CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 72 return false; 73 74 // Check if the only use is a function return node. 75 return isUsedByReturnOnly(Node, Chain); 76 } 77 78 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 79 const uint32_t *CallerPreservedMask, 80 const SmallVectorImpl<CCValAssign> &ArgLocs, 81 const SmallVectorImpl<SDValue> &OutVals) const { 82 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 83 const CCValAssign &ArgLoc = ArgLocs[I]; 84 if (!ArgLoc.isRegLoc()) 85 continue; 86 MCRegister Reg = ArgLoc.getLocReg(); 87 // Only look at callee saved registers. 88 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 89 continue; 90 // Check that we pass the value used for the caller. 91 // (We look for a CopyFromReg reading a virtual register that is used 92 // for the function live-in value of register Reg) 93 SDValue Value = OutVals[I]; 94 if (Value->getOpcode() != ISD::CopyFromReg) 95 return false; 96 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 97 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 98 return false; 99 } 100 return true; 101 } 102 103 /// Set CallLoweringInfo attribute flags based on a call instruction 104 /// and called function attributes. 105 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 106 unsigned ArgIdx) { 107 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 108 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 109 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 110 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 111 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 112 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 113 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 114 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 115 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 116 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 117 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 118 Alignment = Call->getParamStackAlign(ArgIdx); 119 ByValType = nullptr; 120 if (IsByVal) { 121 ByValType = Call->getParamByValType(ArgIdx); 122 if (!Alignment) 123 Alignment = Call->getParamAlign(ArgIdx); 124 } 125 PreallocatedType = nullptr; 126 if (IsPreallocated) 127 PreallocatedType = Call->getParamPreallocatedType(ArgIdx); 128 } 129 130 /// Generate a libcall taking the given operands as arguments and returning a 131 /// result of type RetVT. 132 std::pair<SDValue, SDValue> 133 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 134 ArrayRef<SDValue> Ops, 135 MakeLibCallOptions CallOptions, 136 const SDLoc &dl, 137 SDValue InChain) const { 138 if (!InChain) 139 InChain = DAG.getEntryNode(); 140 141 TargetLowering::ArgListTy Args; 142 Args.reserve(Ops.size()); 143 144 TargetLowering::ArgListEntry Entry; 145 for (unsigned i = 0; i < Ops.size(); ++i) { 146 SDValue NewOp = Ops[i]; 147 Entry.Node = NewOp; 148 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 149 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 150 CallOptions.IsSExt); 151 Entry.IsZExt = !Entry.IsSExt; 152 153 if (CallOptions.IsSoften && 154 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 155 Entry.IsSExt = Entry.IsZExt = false; 156 } 157 Args.push_back(Entry); 158 } 159 160 if (LC == RTLIB::UNKNOWN_LIBCALL) 161 report_fatal_error("Unsupported library call operation!"); 162 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 163 getPointerTy(DAG.getDataLayout())); 164 165 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 166 TargetLowering::CallLoweringInfo CLI(DAG); 167 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 168 bool zeroExtend = !signExtend; 169 170 if (CallOptions.IsSoften && 171 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 172 signExtend = zeroExtend = false; 173 } 174 175 CLI.setDebugLoc(dl) 176 .setChain(InChain) 177 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 178 .setNoReturn(CallOptions.DoesNotReturn) 179 .setDiscardResult(!CallOptions.IsReturnValueUsed) 180 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 181 .setSExtResult(signExtend) 182 .setZExtResult(zeroExtend); 183 return LowerCallTo(CLI); 184 } 185 186 bool TargetLowering::findOptimalMemOpLowering( 187 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 188 unsigned SrcAS, const AttributeList &FuncAttributes) const { 189 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 190 return false; 191 192 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 193 194 if (VT == MVT::Other) { 195 // Use the largest integer type whose alignment constraints are satisfied. 196 // We only need to check DstAlign here as SrcAlign is always greater or 197 // equal to DstAlign (or zero). 198 VT = MVT::i64; 199 if (Op.isFixedDstAlign()) 200 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 201 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 202 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 203 assert(VT.isInteger()); 204 205 // Find the largest legal integer type. 206 MVT LVT = MVT::i64; 207 while (!isTypeLegal(LVT)) 208 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 209 assert(LVT.isInteger()); 210 211 // If the type we've chosen is larger than the largest legal integer type 212 // then use that instead. 213 if (VT.bitsGT(LVT)) 214 VT = LVT; 215 } 216 217 unsigned NumMemOps = 0; 218 uint64_t Size = Op.size(); 219 while (Size) { 220 unsigned VTSize = VT.getSizeInBits() / 8; 221 while (VTSize > Size) { 222 // For now, only use non-vector load / store's for the left-over pieces. 223 EVT NewVT = VT; 224 unsigned NewVTSize; 225 226 bool Found = false; 227 if (VT.isVector() || VT.isFloatingPoint()) { 228 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 229 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 230 isSafeMemOpType(NewVT.getSimpleVT())) 231 Found = true; 232 else if (NewVT == MVT::i64 && 233 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 234 isSafeMemOpType(MVT::f64)) { 235 // i64 is usually not legal on 32-bit targets, but f64 may be. 236 NewVT = MVT::f64; 237 Found = true; 238 } 239 } 240 241 if (!Found) { 242 do { 243 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 244 if (NewVT == MVT::i8) 245 break; 246 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 247 } 248 NewVTSize = NewVT.getSizeInBits() / 8; 249 250 // If the new VT cannot cover all of the remaining bits, then consider 251 // issuing a (or a pair of) unaligned and overlapping load / store. 252 bool Fast; 253 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 254 allowsMisalignedMemoryAccesses( 255 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 256 MachineMemOperand::MONone, &Fast) && 257 Fast) 258 VTSize = Size; 259 else { 260 VT = NewVT; 261 VTSize = NewVTSize; 262 } 263 } 264 265 if (++NumMemOps > Limit) 266 return false; 267 268 MemOps.push_back(VT); 269 Size -= VTSize; 270 } 271 272 return true; 273 } 274 275 /// Soften the operands of a comparison. This code is shared among BR_CC, 276 /// SELECT_CC, and SETCC handlers. 277 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 278 SDValue &NewLHS, SDValue &NewRHS, 279 ISD::CondCode &CCCode, 280 const SDLoc &dl, const SDValue OldLHS, 281 const SDValue OldRHS) const { 282 SDValue Chain; 283 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 284 OldRHS, Chain); 285 } 286 287 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 288 SDValue &NewLHS, SDValue &NewRHS, 289 ISD::CondCode &CCCode, 290 const SDLoc &dl, const SDValue OldLHS, 291 const SDValue OldRHS, 292 SDValue &Chain, 293 bool IsSignaling) const { 294 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 295 // not supporting it. We can update this code when libgcc provides such 296 // functions. 297 298 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 299 && "Unsupported setcc type!"); 300 301 // Expand into one or more soft-fp libcall(s). 302 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 303 bool ShouldInvertCC = false; 304 switch (CCCode) { 305 case ISD::SETEQ: 306 case ISD::SETOEQ: 307 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 308 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 309 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 310 break; 311 case ISD::SETNE: 312 case ISD::SETUNE: 313 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 314 (VT == MVT::f64) ? RTLIB::UNE_F64 : 315 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 316 break; 317 case ISD::SETGE: 318 case ISD::SETOGE: 319 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 320 (VT == MVT::f64) ? RTLIB::OGE_F64 : 321 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 322 break; 323 case ISD::SETLT: 324 case ISD::SETOLT: 325 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 326 (VT == MVT::f64) ? RTLIB::OLT_F64 : 327 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 328 break; 329 case ISD::SETLE: 330 case ISD::SETOLE: 331 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 332 (VT == MVT::f64) ? RTLIB::OLE_F64 : 333 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 334 break; 335 case ISD::SETGT: 336 case ISD::SETOGT: 337 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 338 (VT == MVT::f64) ? RTLIB::OGT_F64 : 339 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 340 break; 341 case ISD::SETO: 342 ShouldInvertCC = true; 343 LLVM_FALLTHROUGH; 344 case ISD::SETUO: 345 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 346 (VT == MVT::f64) ? RTLIB::UO_F64 : 347 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 348 break; 349 case ISD::SETONE: 350 // SETONE = O && UNE 351 ShouldInvertCC = true; 352 LLVM_FALLTHROUGH; 353 case ISD::SETUEQ: 354 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 355 (VT == MVT::f64) ? RTLIB::UO_F64 : 356 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 357 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 358 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 359 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 360 break; 361 default: 362 // Invert CC for unordered comparisons 363 ShouldInvertCC = true; 364 switch (CCCode) { 365 case ISD::SETULT: 366 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 367 (VT == MVT::f64) ? RTLIB::OGE_F64 : 368 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 369 break; 370 case ISD::SETULE: 371 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 372 (VT == MVT::f64) ? RTLIB::OGT_F64 : 373 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 374 break; 375 case ISD::SETUGT: 376 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 377 (VT == MVT::f64) ? RTLIB::OLE_F64 : 378 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 379 break; 380 case ISD::SETUGE: 381 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 382 (VT == MVT::f64) ? RTLIB::OLT_F64 : 383 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 384 break; 385 default: llvm_unreachable("Do not know how to soften this setcc!"); 386 } 387 } 388 389 // Use the target specific return value for comparions lib calls. 390 EVT RetVT = getCmpLibcallReturnType(); 391 SDValue Ops[2] = {NewLHS, NewRHS}; 392 TargetLowering::MakeLibCallOptions CallOptions; 393 EVT OpsVT[2] = { OldLHS.getValueType(), 394 OldRHS.getValueType() }; 395 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 396 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 397 NewLHS = Call.first; 398 NewRHS = DAG.getConstant(0, dl, RetVT); 399 400 CCCode = getCmpLibcallCC(LC1); 401 if (ShouldInvertCC) { 402 assert(RetVT.isInteger()); 403 CCCode = getSetCCInverse(CCCode, RetVT); 404 } 405 406 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 407 // Update Chain. 408 Chain = Call.second; 409 } else { 410 EVT SetCCVT = 411 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 412 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 413 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 414 CCCode = getCmpLibcallCC(LC2); 415 if (ShouldInvertCC) 416 CCCode = getSetCCInverse(CCCode, RetVT); 417 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 418 if (Chain) 419 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 420 Call2.second); 421 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 422 Tmp.getValueType(), Tmp, NewLHS); 423 NewRHS = SDValue(); 424 } 425 } 426 427 /// Return the entry encoding for a jump table in the current function. The 428 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 429 unsigned TargetLowering::getJumpTableEncoding() const { 430 // In non-pic modes, just use the address of a block. 431 if (!isPositionIndependent()) 432 return MachineJumpTableInfo::EK_BlockAddress; 433 434 // In PIC mode, if the target supports a GPRel32 directive, use it. 435 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 436 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 437 438 // Otherwise, use a label difference. 439 return MachineJumpTableInfo::EK_LabelDifference32; 440 } 441 442 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 443 SelectionDAG &DAG) const { 444 // If our PIC model is GP relative, use the global offset table as the base. 445 unsigned JTEncoding = getJumpTableEncoding(); 446 447 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 448 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 449 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 450 451 return Table; 452 } 453 454 /// This returns the relocation base for the given PIC jumptable, the same as 455 /// getPICJumpTableRelocBase, but as an MCExpr. 456 const MCExpr * 457 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 458 unsigned JTI,MCContext &Ctx) const{ 459 // The normal PIC reloc base is the label at the start of the jump table. 460 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 461 } 462 463 bool 464 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 465 const TargetMachine &TM = getTargetMachine(); 466 const GlobalValue *GV = GA->getGlobal(); 467 468 // If the address is not even local to this DSO we will have to load it from 469 // a got and then add the offset. 470 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 471 return false; 472 473 // If the code is position independent we will have to add a base register. 474 if (isPositionIndependent()) 475 return false; 476 477 // Otherwise we can do it. 478 return true; 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Optimization Methods 483 //===----------------------------------------------------------------------===// 484 485 /// If the specified instruction has a constant integer operand and there are 486 /// bits set in that constant that are not demanded, then clear those bits and 487 /// return true. 488 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 489 const APInt &DemandedBits, 490 const APInt &DemandedElts, 491 TargetLoweringOpt &TLO) const { 492 SDLoc DL(Op); 493 unsigned Opcode = Op.getOpcode(); 494 495 // Do target-specific constant optimization. 496 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 497 return TLO.New.getNode(); 498 499 // FIXME: ISD::SELECT, ISD::SELECT_CC 500 switch (Opcode) { 501 default: 502 break; 503 case ISD::XOR: 504 case ISD::AND: 505 case ISD::OR: { 506 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 507 if (!Op1C) 508 return false; 509 510 // If this is a 'not' op, don't touch it because that's a canonical form. 511 const APInt &C = Op1C->getAPIntValue(); 512 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 513 return false; 514 515 if (!C.isSubsetOf(DemandedBits)) { 516 EVT VT = Op.getValueType(); 517 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 518 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 519 return TLO.CombineTo(Op, NewOp); 520 } 521 522 break; 523 } 524 } 525 526 return false; 527 } 528 529 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 530 const APInt &DemandedBits, 531 TargetLoweringOpt &TLO) const { 532 EVT VT = Op.getValueType(); 533 APInt DemandedElts = VT.isVector() 534 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 535 : APInt(1, 1); 536 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 537 } 538 539 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 540 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 541 /// generalized for targets with other types of implicit widening casts. 542 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 543 const APInt &Demanded, 544 TargetLoweringOpt &TLO) const { 545 assert(Op.getNumOperands() == 2 && 546 "ShrinkDemandedOp only supports binary operators!"); 547 assert(Op.getNode()->getNumValues() == 1 && 548 "ShrinkDemandedOp only supports nodes with one result!"); 549 550 SelectionDAG &DAG = TLO.DAG; 551 SDLoc dl(Op); 552 553 // Early return, as this function cannot handle vector types. 554 if (Op.getValueType().isVector()) 555 return false; 556 557 // Don't do this if the node has another user, which may require the 558 // full value. 559 if (!Op.getNode()->hasOneUse()) 560 return false; 561 562 // Search for the smallest integer type with free casts to and from 563 // Op's type. For expedience, just check power-of-2 integer types. 564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 565 unsigned DemandedSize = Demanded.getActiveBits(); 566 unsigned SmallVTBits = DemandedSize; 567 if (!isPowerOf2_32(SmallVTBits)) 568 SmallVTBits = NextPowerOf2(SmallVTBits); 569 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 570 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 571 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 572 TLI.isZExtFree(SmallVT, Op.getValueType())) { 573 // We found a type with free casts. 574 SDValue X = DAG.getNode( 575 Op.getOpcode(), dl, SmallVT, 576 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 577 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 578 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 579 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 580 return TLO.CombineTo(Op, Z); 581 } 582 } 583 return false; 584 } 585 586 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 587 DAGCombinerInfo &DCI) const { 588 SelectionDAG &DAG = DCI.DAG; 589 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 590 !DCI.isBeforeLegalizeOps()); 591 KnownBits Known; 592 593 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 594 if (Simplified) { 595 DCI.AddToWorklist(Op.getNode()); 596 DCI.CommitTargetLoweringOpt(TLO); 597 } 598 return Simplified; 599 } 600 601 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 602 KnownBits &Known, 603 TargetLoweringOpt &TLO, 604 unsigned Depth, 605 bool AssumeSingleUse) const { 606 EVT VT = Op.getValueType(); 607 608 // TODO: We can probably do more work on calculating the known bits and 609 // simplifying the operations for scalable vectors, but for now we just 610 // bail out. 611 if (VT.isScalableVector()) { 612 // Pretend we don't know anything for now. 613 Known = KnownBits(DemandedBits.getBitWidth()); 614 return false; 615 } 616 617 APInt DemandedElts = VT.isVector() 618 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 619 : APInt(1, 1); 620 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 621 AssumeSingleUse); 622 } 623 624 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 625 // TODO: Under what circumstances can we create nodes? Constant folding? 626 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 627 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 628 SelectionDAG &DAG, unsigned Depth) const { 629 // Limit search depth. 630 if (Depth >= SelectionDAG::MaxRecursionDepth) 631 return SDValue(); 632 633 // Ignore UNDEFs. 634 if (Op.isUndef()) 635 return SDValue(); 636 637 // Not demanding any bits/elts from Op. 638 if (DemandedBits == 0 || DemandedElts == 0) 639 return DAG.getUNDEF(Op.getValueType()); 640 641 unsigned NumElts = DemandedElts.getBitWidth(); 642 unsigned BitWidth = DemandedBits.getBitWidth(); 643 KnownBits LHSKnown, RHSKnown; 644 switch (Op.getOpcode()) { 645 case ISD::BITCAST: { 646 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 647 EVT SrcVT = Src.getValueType(); 648 EVT DstVT = Op.getValueType(); 649 if (SrcVT == DstVT) 650 return Src; 651 652 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 653 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 654 if (NumSrcEltBits == NumDstEltBits) 655 if (SDValue V = SimplifyMultipleUseDemandedBits( 656 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 657 return DAG.getBitcast(DstVT, V); 658 659 // TODO - bigendian once we have test coverage. 660 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 && 661 DAG.getDataLayout().isLittleEndian()) { 662 unsigned Scale = NumDstEltBits / NumSrcEltBits; 663 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 664 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 665 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 666 for (unsigned i = 0; i != Scale; ++i) { 667 unsigned Offset = i * NumSrcEltBits; 668 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 669 if (!Sub.isNullValue()) { 670 DemandedSrcBits |= Sub; 671 for (unsigned j = 0; j != NumElts; ++j) 672 if (DemandedElts[j]) 673 DemandedSrcElts.setBit((j * Scale) + i); 674 } 675 } 676 677 if (SDValue V = SimplifyMultipleUseDemandedBits( 678 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 679 return DAG.getBitcast(DstVT, V); 680 } 681 682 // TODO - bigendian once we have test coverage. 683 if ((NumSrcEltBits % NumDstEltBits) == 0 && 684 DAG.getDataLayout().isLittleEndian()) { 685 unsigned Scale = NumSrcEltBits / NumDstEltBits; 686 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 687 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 688 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 689 for (unsigned i = 0; i != NumElts; ++i) 690 if (DemandedElts[i]) { 691 unsigned Offset = (i % Scale) * NumDstEltBits; 692 DemandedSrcBits.insertBits(DemandedBits, Offset); 693 DemandedSrcElts.setBit(i / Scale); 694 } 695 696 if (SDValue V = SimplifyMultipleUseDemandedBits( 697 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 698 return DAG.getBitcast(DstVT, V); 699 } 700 701 break; 702 } 703 case ISD::AND: { 704 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 705 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 706 707 // If all of the demanded bits are known 1 on one side, return the other. 708 // These bits cannot contribute to the result of the 'and' in this 709 // context. 710 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 711 return Op.getOperand(0); 712 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 713 return Op.getOperand(1); 714 break; 715 } 716 case ISD::OR: { 717 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 718 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 719 720 // If all of the demanded bits are known zero on one side, return the 721 // other. These bits cannot contribute to the result of the 'or' in this 722 // context. 723 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 724 return Op.getOperand(0); 725 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 726 return Op.getOperand(1); 727 break; 728 } 729 case ISD::XOR: { 730 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 731 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 732 733 // If all of the demanded bits are known zero on one side, return the 734 // other. 735 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 736 return Op.getOperand(0); 737 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 738 return Op.getOperand(1); 739 break; 740 } 741 case ISD::SHL: { 742 // If we are only demanding sign bits then we can use the shift source 743 // directly. 744 if (const APInt *MaxSA = 745 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 746 SDValue Op0 = Op.getOperand(0); 747 unsigned ShAmt = MaxSA->getZExtValue(); 748 unsigned NumSignBits = 749 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 750 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 751 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 752 return Op0; 753 } 754 break; 755 } 756 case ISD::SETCC: { 757 SDValue Op0 = Op.getOperand(0); 758 SDValue Op1 = Op.getOperand(1); 759 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 760 // If (1) we only need the sign-bit, (2) the setcc operands are the same 761 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 762 // -1, we may be able to bypass the setcc. 763 if (DemandedBits.isSignMask() && 764 Op0.getScalarValueSizeInBits() == BitWidth && 765 getBooleanContents(Op0.getValueType()) == 766 BooleanContent::ZeroOrNegativeOneBooleanContent) { 767 // If we're testing X < 0, then this compare isn't needed - just use X! 768 // FIXME: We're limiting to integer types here, but this should also work 769 // if we don't care about FP signed-zero. The use of SETLT with FP means 770 // that we don't care about NaNs. 771 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 772 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 773 return Op0; 774 } 775 break; 776 } 777 case ISD::SIGN_EXTEND_INREG: { 778 // If none of the extended bits are demanded, eliminate the sextinreg. 779 SDValue Op0 = Op.getOperand(0); 780 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 781 unsigned ExBits = ExVT.getScalarSizeInBits(); 782 if (DemandedBits.getActiveBits() <= ExBits) 783 return Op0; 784 // If the input is already sign extended, just drop the extension. 785 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 786 if (NumSignBits >= (BitWidth - ExBits + 1)) 787 return Op0; 788 break; 789 } 790 case ISD::ANY_EXTEND_VECTOR_INREG: 791 case ISD::SIGN_EXTEND_VECTOR_INREG: 792 case ISD::ZERO_EXTEND_VECTOR_INREG: { 793 // If we only want the lowest element and none of extended bits, then we can 794 // return the bitcasted source vector. 795 SDValue Src = Op.getOperand(0); 796 EVT SrcVT = Src.getValueType(); 797 EVT DstVT = Op.getValueType(); 798 if (DemandedElts == 1 && DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 799 DAG.getDataLayout().isLittleEndian() && 800 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 801 return DAG.getBitcast(DstVT, Src); 802 } 803 break; 804 } 805 case ISD::INSERT_VECTOR_ELT: { 806 // If we don't demand the inserted element, return the base vector. 807 SDValue Vec = Op.getOperand(0); 808 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 809 EVT VecVT = Vec.getValueType(); 810 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 811 !DemandedElts[CIdx->getZExtValue()]) 812 return Vec; 813 break; 814 } 815 case ISD::INSERT_SUBVECTOR: { 816 // If we don't demand the inserted subvector, return the base vector. 817 SDValue Vec = Op.getOperand(0); 818 SDValue Sub = Op.getOperand(1); 819 uint64_t Idx = Op.getConstantOperandVal(2); 820 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 821 if (DemandedElts.extractBits(NumSubElts, Idx) == 0) 822 return Vec; 823 break; 824 } 825 case ISD::VECTOR_SHUFFLE: { 826 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 827 828 // If all the demanded elts are from one operand and are inline, 829 // then we can use the operand directly. 830 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 831 for (unsigned i = 0; i != NumElts; ++i) { 832 int M = ShuffleMask[i]; 833 if (M < 0 || !DemandedElts[i]) 834 continue; 835 AllUndef = false; 836 IdentityLHS &= (M == (int)i); 837 IdentityRHS &= ((M - NumElts) == i); 838 } 839 840 if (AllUndef) 841 return DAG.getUNDEF(Op.getValueType()); 842 if (IdentityLHS) 843 return Op.getOperand(0); 844 if (IdentityRHS) 845 return Op.getOperand(1); 846 break; 847 } 848 default: 849 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 850 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 851 Op, DemandedBits, DemandedElts, DAG, Depth)) 852 return V; 853 break; 854 } 855 return SDValue(); 856 } 857 858 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 859 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 860 unsigned Depth) const { 861 EVT VT = Op.getValueType(); 862 APInt DemandedElts = VT.isVector() 863 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 864 : APInt(1, 1); 865 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 866 Depth); 867 } 868 869 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 870 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 871 unsigned Depth) const { 872 APInt DemandedBits = APInt::getAllOnesValue(Op.getScalarValueSizeInBits()); 873 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 874 Depth); 875 } 876 877 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 878 /// result of Op are ever used downstream. If we can use this information to 879 /// simplify Op, create a new simplified DAG node and return true, returning the 880 /// original and new nodes in Old and New. Otherwise, analyze the expression and 881 /// return a mask of Known bits for the expression (used to simplify the 882 /// caller). The Known bits may only be accurate for those bits in the 883 /// OriginalDemandedBits and OriginalDemandedElts. 884 bool TargetLowering::SimplifyDemandedBits( 885 SDValue Op, const APInt &OriginalDemandedBits, 886 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 887 unsigned Depth, bool AssumeSingleUse) const { 888 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 889 assert(Op.getScalarValueSizeInBits() == BitWidth && 890 "Mask size mismatches value type size!"); 891 892 // Don't know anything. 893 Known = KnownBits(BitWidth); 894 895 // TODO: We can probably do more work on calculating the known bits and 896 // simplifying the operations for scalable vectors, but for now we just 897 // bail out. 898 if (Op.getValueType().isScalableVector()) 899 return false; 900 901 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 902 assert((!Op.getValueType().isVector() || 903 NumElts == Op.getValueType().getVectorNumElements()) && 904 "Unexpected vector size"); 905 906 APInt DemandedBits = OriginalDemandedBits; 907 APInt DemandedElts = OriginalDemandedElts; 908 SDLoc dl(Op); 909 auto &DL = TLO.DAG.getDataLayout(); 910 911 // Undef operand. 912 if (Op.isUndef()) 913 return false; 914 915 if (Op.getOpcode() == ISD::Constant) { 916 // We know all of the bits for a constant! 917 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 918 return false; 919 } 920 921 if (Op.getOpcode() == ISD::ConstantFP) { 922 // We know all of the bits for a floating point constant! 923 Known = KnownBits::makeConstant( 924 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 925 return false; 926 } 927 928 // Other users may use these bits. 929 EVT VT = Op.getValueType(); 930 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 931 if (Depth != 0) { 932 // If not at the root, Just compute the Known bits to 933 // simplify things downstream. 934 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 935 return false; 936 } 937 // If this is the root being simplified, allow it to have multiple uses, 938 // just set the DemandedBits/Elts to all bits. 939 DemandedBits = APInt::getAllOnesValue(BitWidth); 940 DemandedElts = APInt::getAllOnesValue(NumElts); 941 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 942 // Not demanding any bits/elts from Op. 943 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 944 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 945 // Limit search depth. 946 return false; 947 } 948 949 KnownBits Known2; 950 switch (Op.getOpcode()) { 951 case ISD::TargetConstant: 952 llvm_unreachable("Can't simplify this node"); 953 case ISD::SCALAR_TO_VECTOR: { 954 if (!DemandedElts[0]) 955 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 956 957 KnownBits SrcKnown; 958 SDValue Src = Op.getOperand(0); 959 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 960 APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth); 961 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 962 return true; 963 964 // Upper elements are undef, so only get the knownbits if we just demand 965 // the bottom element. 966 if (DemandedElts == 1) 967 Known = SrcKnown.anyextOrTrunc(BitWidth); 968 break; 969 } 970 case ISD::BUILD_VECTOR: 971 // Collect the known bits that are shared by every demanded element. 972 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 973 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 974 return false; // Don't fall through, will infinitely loop. 975 case ISD::LOAD: { 976 auto *LD = cast<LoadSDNode>(Op); 977 if (getTargetConstantFromLoad(LD)) { 978 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 979 return false; // Don't fall through, will infinitely loop. 980 } 981 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 982 // If this is a ZEXTLoad and we are looking at the loaded value. 983 EVT MemVT = LD->getMemoryVT(); 984 unsigned MemBits = MemVT.getScalarSizeInBits(); 985 Known.Zero.setBitsFrom(MemBits); 986 return false; // Don't fall through, will infinitely loop. 987 } 988 break; 989 } 990 case ISD::INSERT_VECTOR_ELT: { 991 SDValue Vec = Op.getOperand(0); 992 SDValue Scl = Op.getOperand(1); 993 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 994 EVT VecVT = Vec.getValueType(); 995 996 // If index isn't constant, assume we need all vector elements AND the 997 // inserted element. 998 APInt DemandedVecElts(DemandedElts); 999 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1000 unsigned Idx = CIdx->getZExtValue(); 1001 DemandedVecElts.clearBit(Idx); 1002 1003 // Inserted element is not required. 1004 if (!DemandedElts[Idx]) 1005 return TLO.CombineTo(Op, Vec); 1006 } 1007 1008 KnownBits KnownScl; 1009 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1010 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1011 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1012 return true; 1013 1014 Known = KnownScl.anyextOrTrunc(BitWidth); 1015 1016 KnownBits KnownVec; 1017 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1018 Depth + 1)) 1019 return true; 1020 1021 if (!!DemandedVecElts) 1022 Known = KnownBits::commonBits(Known, KnownVec); 1023 1024 return false; 1025 } 1026 case ISD::INSERT_SUBVECTOR: { 1027 // Demand any elements from the subvector and the remainder from the src its 1028 // inserted into. 1029 SDValue Src = Op.getOperand(0); 1030 SDValue Sub = Op.getOperand(1); 1031 uint64_t Idx = Op.getConstantOperandVal(2); 1032 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1033 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1034 APInt DemandedSrcElts = DemandedElts; 1035 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 1036 1037 KnownBits KnownSub, KnownSrc; 1038 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1039 Depth + 1)) 1040 return true; 1041 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1042 Depth + 1)) 1043 return true; 1044 1045 Known.Zero.setAllBits(); 1046 Known.One.setAllBits(); 1047 if (!!DemandedSubElts) 1048 Known = KnownBits::commonBits(Known, KnownSub); 1049 if (!!DemandedSrcElts) 1050 Known = KnownBits::commonBits(Known, KnownSrc); 1051 1052 // Attempt to avoid multi-use src if we don't need anything from it. 1053 if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() || 1054 !DemandedSrcElts.isAllOnesValue()) { 1055 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1056 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1057 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1058 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1059 if (NewSub || NewSrc) { 1060 NewSub = NewSub ? NewSub : Sub; 1061 NewSrc = NewSrc ? NewSrc : Src; 1062 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1063 Op.getOperand(2)); 1064 return TLO.CombineTo(Op, NewOp); 1065 } 1066 } 1067 break; 1068 } 1069 case ISD::EXTRACT_SUBVECTOR: { 1070 // Offset the demanded elts by the subvector index. 1071 SDValue Src = Op.getOperand(0); 1072 if (Src.getValueType().isScalableVector()) 1073 break; 1074 uint64_t Idx = Op.getConstantOperandVal(1); 1075 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1076 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1077 1078 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1079 Depth + 1)) 1080 return true; 1081 1082 // Attempt to avoid multi-use src if we don't need anything from it. 1083 if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) { 1084 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1085 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1086 if (DemandedSrc) { 1087 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1088 Op.getOperand(1)); 1089 return TLO.CombineTo(Op, NewOp); 1090 } 1091 } 1092 break; 1093 } 1094 case ISD::CONCAT_VECTORS: { 1095 Known.Zero.setAllBits(); 1096 Known.One.setAllBits(); 1097 EVT SubVT = Op.getOperand(0).getValueType(); 1098 unsigned NumSubVecs = Op.getNumOperands(); 1099 unsigned NumSubElts = SubVT.getVectorNumElements(); 1100 for (unsigned i = 0; i != NumSubVecs; ++i) { 1101 APInt DemandedSubElts = 1102 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1103 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1104 Known2, TLO, Depth + 1)) 1105 return true; 1106 // Known bits are shared by every demanded subvector element. 1107 if (!!DemandedSubElts) 1108 Known = KnownBits::commonBits(Known, Known2); 1109 } 1110 break; 1111 } 1112 case ISD::VECTOR_SHUFFLE: { 1113 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1114 1115 // Collect demanded elements from shuffle operands.. 1116 APInt DemandedLHS(NumElts, 0); 1117 APInt DemandedRHS(NumElts, 0); 1118 for (unsigned i = 0; i != NumElts; ++i) { 1119 if (!DemandedElts[i]) 1120 continue; 1121 int M = ShuffleMask[i]; 1122 if (M < 0) { 1123 // For UNDEF elements, we don't know anything about the common state of 1124 // the shuffle result. 1125 DemandedLHS.clearAllBits(); 1126 DemandedRHS.clearAllBits(); 1127 break; 1128 } 1129 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1130 if (M < (int)NumElts) 1131 DemandedLHS.setBit(M); 1132 else 1133 DemandedRHS.setBit(M - NumElts); 1134 } 1135 1136 if (!!DemandedLHS || !!DemandedRHS) { 1137 SDValue Op0 = Op.getOperand(0); 1138 SDValue Op1 = Op.getOperand(1); 1139 1140 Known.Zero.setAllBits(); 1141 Known.One.setAllBits(); 1142 if (!!DemandedLHS) { 1143 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1144 Depth + 1)) 1145 return true; 1146 Known = KnownBits::commonBits(Known, Known2); 1147 } 1148 if (!!DemandedRHS) { 1149 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1150 Depth + 1)) 1151 return true; 1152 Known = KnownBits::commonBits(Known, Known2); 1153 } 1154 1155 // Attempt to avoid multi-use ops if we don't need anything from them. 1156 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1157 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1158 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1159 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1160 if (DemandedOp0 || DemandedOp1) { 1161 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1162 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1163 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1164 return TLO.CombineTo(Op, NewOp); 1165 } 1166 } 1167 break; 1168 } 1169 case ISD::AND: { 1170 SDValue Op0 = Op.getOperand(0); 1171 SDValue Op1 = Op.getOperand(1); 1172 1173 // If the RHS is a constant, check to see if the LHS would be zero without 1174 // using the bits from the RHS. Below, we use knowledge about the RHS to 1175 // simplify the LHS, here we're using information from the LHS to simplify 1176 // the RHS. 1177 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1178 // Do not increment Depth here; that can cause an infinite loop. 1179 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1180 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1181 if ((LHSKnown.Zero & DemandedBits) == 1182 (~RHSC->getAPIntValue() & DemandedBits)) 1183 return TLO.CombineTo(Op, Op0); 1184 1185 // If any of the set bits in the RHS are known zero on the LHS, shrink 1186 // the constant. 1187 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1188 DemandedElts, TLO)) 1189 return true; 1190 1191 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1192 // constant, but if this 'and' is only clearing bits that were just set by 1193 // the xor, then this 'and' can be eliminated by shrinking the mask of 1194 // the xor. For example, for a 32-bit X: 1195 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1196 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1197 LHSKnown.One == ~RHSC->getAPIntValue()) { 1198 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1199 return TLO.CombineTo(Op, Xor); 1200 } 1201 } 1202 1203 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1204 Depth + 1)) 1205 return true; 1206 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1207 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1208 Known2, TLO, Depth + 1)) 1209 return true; 1210 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1211 1212 // Attempt to avoid multi-use ops if we don't need anything from them. 1213 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1214 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1215 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1216 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1217 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1218 if (DemandedOp0 || DemandedOp1) { 1219 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1220 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1221 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1222 return TLO.CombineTo(Op, NewOp); 1223 } 1224 } 1225 1226 // If all of the demanded bits are known one on one side, return the other. 1227 // These bits cannot contribute to the result of the 'and'. 1228 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1229 return TLO.CombineTo(Op, Op0); 1230 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1231 return TLO.CombineTo(Op, Op1); 1232 // If all of the demanded bits in the inputs are known zeros, return zero. 1233 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1234 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1235 // If the RHS is a constant, see if we can simplify it. 1236 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1237 TLO)) 1238 return true; 1239 // If the operation can be done in a smaller type, do so. 1240 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1241 return true; 1242 1243 Known &= Known2; 1244 break; 1245 } 1246 case ISD::OR: { 1247 SDValue Op0 = Op.getOperand(0); 1248 SDValue Op1 = Op.getOperand(1); 1249 1250 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1251 Depth + 1)) 1252 return true; 1253 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1254 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1255 Known2, TLO, Depth + 1)) 1256 return true; 1257 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1258 1259 // Attempt to avoid multi-use ops if we don't need anything from them. 1260 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1261 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1262 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1263 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1264 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1265 if (DemandedOp0 || DemandedOp1) { 1266 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1267 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1268 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1269 return TLO.CombineTo(Op, NewOp); 1270 } 1271 } 1272 1273 // If all of the demanded bits are known zero on one side, return the other. 1274 // These bits cannot contribute to the result of the 'or'. 1275 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1276 return TLO.CombineTo(Op, Op0); 1277 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1278 return TLO.CombineTo(Op, Op1); 1279 // If the RHS is a constant, see if we can simplify it. 1280 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1281 return true; 1282 // If the operation can be done in a smaller type, do so. 1283 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1284 return true; 1285 1286 Known |= Known2; 1287 break; 1288 } 1289 case ISD::XOR: { 1290 SDValue Op0 = Op.getOperand(0); 1291 SDValue Op1 = Op.getOperand(1); 1292 1293 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1294 Depth + 1)) 1295 return true; 1296 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1297 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1298 Depth + 1)) 1299 return true; 1300 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1301 1302 // Attempt to avoid multi-use ops if we don't need anything from them. 1303 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1304 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1305 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1306 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1307 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1308 if (DemandedOp0 || DemandedOp1) { 1309 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1310 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1311 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1312 return TLO.CombineTo(Op, NewOp); 1313 } 1314 } 1315 1316 // If all of the demanded bits are known zero on one side, return the other. 1317 // These bits cannot contribute to the result of the 'xor'. 1318 if (DemandedBits.isSubsetOf(Known.Zero)) 1319 return TLO.CombineTo(Op, Op0); 1320 if (DemandedBits.isSubsetOf(Known2.Zero)) 1321 return TLO.CombineTo(Op, Op1); 1322 // If the operation can be done in a smaller type, do so. 1323 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1324 return true; 1325 1326 // If all of the unknown bits are known to be zero on one side or the other 1327 // turn this into an *inclusive* or. 1328 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1329 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1330 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1331 1332 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1333 if (C) { 1334 // If one side is a constant, and all of the set bits in the constant are 1335 // also known set on the other side, turn this into an AND, as we know 1336 // the bits will be cleared. 1337 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1338 // NB: it is okay if more bits are known than are requested 1339 if (C->getAPIntValue() == Known2.One) { 1340 SDValue ANDC = 1341 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1342 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1343 } 1344 1345 // If the RHS is a constant, see if we can change it. Don't alter a -1 1346 // constant because that's a 'not' op, and that is better for combining 1347 // and codegen. 1348 if (!C->isAllOnesValue() && 1349 DemandedBits.isSubsetOf(C->getAPIntValue())) { 1350 // We're flipping all demanded bits. Flip the undemanded bits too. 1351 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1352 return TLO.CombineTo(Op, New); 1353 } 1354 } 1355 1356 // If we can't turn this into a 'not', try to shrink the constant. 1357 if (!C || !C->isAllOnesValue()) 1358 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1359 return true; 1360 1361 Known ^= Known2; 1362 break; 1363 } 1364 case ISD::SELECT: 1365 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1366 Depth + 1)) 1367 return true; 1368 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1369 Depth + 1)) 1370 return true; 1371 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1372 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1373 1374 // If the operands are constants, see if we can simplify them. 1375 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1376 return true; 1377 1378 // Only known if known in both the LHS and RHS. 1379 Known = KnownBits::commonBits(Known, Known2); 1380 break; 1381 case ISD::SELECT_CC: 1382 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1383 Depth + 1)) 1384 return true; 1385 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1386 Depth + 1)) 1387 return true; 1388 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1389 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1390 1391 // If the operands are constants, see if we can simplify them. 1392 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1393 return true; 1394 1395 // Only known if known in both the LHS and RHS. 1396 Known = KnownBits::commonBits(Known, Known2); 1397 break; 1398 case ISD::SETCC: { 1399 SDValue Op0 = Op.getOperand(0); 1400 SDValue Op1 = Op.getOperand(1); 1401 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1402 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1403 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1404 // -1, we may be able to bypass the setcc. 1405 if (DemandedBits.isSignMask() && 1406 Op0.getScalarValueSizeInBits() == BitWidth && 1407 getBooleanContents(Op0.getValueType()) == 1408 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1409 // If we're testing X < 0, then this compare isn't needed - just use X! 1410 // FIXME: We're limiting to integer types here, but this should also work 1411 // if we don't care about FP signed-zero. The use of SETLT with FP means 1412 // that we don't care about NaNs. 1413 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1414 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1415 return TLO.CombineTo(Op, Op0); 1416 1417 // TODO: Should we check for other forms of sign-bit comparisons? 1418 // Examples: X <= -1, X >= 0 1419 } 1420 if (getBooleanContents(Op0.getValueType()) == 1421 TargetLowering::ZeroOrOneBooleanContent && 1422 BitWidth > 1) 1423 Known.Zero.setBitsFrom(1); 1424 break; 1425 } 1426 case ISD::SHL: { 1427 SDValue Op0 = Op.getOperand(0); 1428 SDValue Op1 = Op.getOperand(1); 1429 EVT ShiftVT = Op1.getValueType(); 1430 1431 if (const APInt *SA = 1432 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1433 unsigned ShAmt = SA->getZExtValue(); 1434 if (ShAmt == 0) 1435 return TLO.CombineTo(Op, Op0); 1436 1437 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1438 // single shift. We can do this if the bottom bits (which are shifted 1439 // out) are never demanded. 1440 // TODO - support non-uniform vector amounts. 1441 if (Op0.getOpcode() == ISD::SRL) { 1442 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1443 if (const APInt *SA2 = 1444 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1445 unsigned C1 = SA2->getZExtValue(); 1446 unsigned Opc = ISD::SHL; 1447 int Diff = ShAmt - C1; 1448 if (Diff < 0) { 1449 Diff = -Diff; 1450 Opc = ISD::SRL; 1451 } 1452 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1453 return TLO.CombineTo( 1454 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1455 } 1456 } 1457 } 1458 1459 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1460 // are not demanded. This will likely allow the anyext to be folded away. 1461 // TODO - support non-uniform vector amounts. 1462 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1463 SDValue InnerOp = Op0.getOperand(0); 1464 EVT InnerVT = InnerOp.getValueType(); 1465 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1466 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1467 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1468 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1469 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1470 ShTy = InnerVT; 1471 SDValue NarrowShl = 1472 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1473 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1474 return TLO.CombineTo( 1475 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1476 } 1477 1478 // Repeat the SHL optimization above in cases where an extension 1479 // intervenes: (shl (anyext (shr x, c1)), c2) to 1480 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1481 // aren't demanded (as above) and that the shifted upper c1 bits of 1482 // x aren't demanded. 1483 // TODO - support non-uniform vector amounts. 1484 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1485 InnerOp.hasOneUse()) { 1486 if (const APInt *SA2 = 1487 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1488 unsigned InnerShAmt = SA2->getZExtValue(); 1489 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1490 DemandedBits.getActiveBits() <= 1491 (InnerBits - InnerShAmt + ShAmt) && 1492 DemandedBits.countTrailingZeros() >= ShAmt) { 1493 SDValue NewSA = 1494 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1495 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1496 InnerOp.getOperand(0)); 1497 return TLO.CombineTo( 1498 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1499 } 1500 } 1501 } 1502 } 1503 1504 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1505 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1506 Depth + 1)) 1507 return true; 1508 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1509 Known.Zero <<= ShAmt; 1510 Known.One <<= ShAmt; 1511 // low bits known zero. 1512 Known.Zero.setLowBits(ShAmt); 1513 1514 // Try shrinking the operation as long as the shift amount will still be 1515 // in range. 1516 if ((ShAmt < DemandedBits.getActiveBits()) && 1517 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1518 return true; 1519 } 1520 1521 // If we are only demanding sign bits then we can use the shift source 1522 // directly. 1523 if (const APInt *MaxSA = 1524 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1525 unsigned ShAmt = MaxSA->getZExtValue(); 1526 unsigned NumSignBits = 1527 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1528 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1529 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1530 return TLO.CombineTo(Op, Op0); 1531 } 1532 break; 1533 } 1534 case ISD::SRL: { 1535 SDValue Op0 = Op.getOperand(0); 1536 SDValue Op1 = Op.getOperand(1); 1537 EVT ShiftVT = Op1.getValueType(); 1538 1539 if (const APInt *SA = 1540 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1541 unsigned ShAmt = SA->getZExtValue(); 1542 if (ShAmt == 0) 1543 return TLO.CombineTo(Op, Op0); 1544 1545 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1546 // single shift. We can do this if the top bits (which are shifted out) 1547 // are never demanded. 1548 // TODO - support non-uniform vector amounts. 1549 if (Op0.getOpcode() == ISD::SHL) { 1550 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1551 if (const APInt *SA2 = 1552 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1553 unsigned C1 = SA2->getZExtValue(); 1554 unsigned Opc = ISD::SRL; 1555 int Diff = ShAmt - C1; 1556 if (Diff < 0) { 1557 Diff = -Diff; 1558 Opc = ISD::SHL; 1559 } 1560 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1561 return TLO.CombineTo( 1562 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1563 } 1564 } 1565 } 1566 1567 APInt InDemandedMask = (DemandedBits << ShAmt); 1568 1569 // If the shift is exact, then it does demand the low bits (and knows that 1570 // they are zero). 1571 if (Op->getFlags().hasExact()) 1572 InDemandedMask.setLowBits(ShAmt); 1573 1574 // Compute the new bits that are at the top now. 1575 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1576 Depth + 1)) 1577 return true; 1578 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1579 Known.Zero.lshrInPlace(ShAmt); 1580 Known.One.lshrInPlace(ShAmt); 1581 // High bits known zero. 1582 Known.Zero.setHighBits(ShAmt); 1583 } 1584 break; 1585 } 1586 case ISD::SRA: { 1587 SDValue Op0 = Op.getOperand(0); 1588 SDValue Op1 = Op.getOperand(1); 1589 EVT ShiftVT = Op1.getValueType(); 1590 1591 // If we only want bits that already match the signbit then we don't need 1592 // to shift. 1593 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1594 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1595 NumHiDemandedBits) 1596 return TLO.CombineTo(Op, Op0); 1597 1598 // If this is an arithmetic shift right and only the low-bit is set, we can 1599 // always convert this into a logical shr, even if the shift amount is 1600 // variable. The low bit of the shift cannot be an input sign bit unless 1601 // the shift amount is >= the size of the datatype, which is undefined. 1602 if (DemandedBits.isOneValue()) 1603 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1604 1605 if (const APInt *SA = 1606 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1607 unsigned ShAmt = SA->getZExtValue(); 1608 if (ShAmt == 0) 1609 return TLO.CombineTo(Op, Op0); 1610 1611 APInt InDemandedMask = (DemandedBits << ShAmt); 1612 1613 // If the shift is exact, then it does demand the low bits (and knows that 1614 // they are zero). 1615 if (Op->getFlags().hasExact()) 1616 InDemandedMask.setLowBits(ShAmt); 1617 1618 // If any of the demanded bits are produced by the sign extension, we also 1619 // demand the input sign bit. 1620 if (DemandedBits.countLeadingZeros() < ShAmt) 1621 InDemandedMask.setSignBit(); 1622 1623 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1624 Depth + 1)) 1625 return true; 1626 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1627 Known.Zero.lshrInPlace(ShAmt); 1628 Known.One.lshrInPlace(ShAmt); 1629 1630 // If the input sign bit is known to be zero, or if none of the top bits 1631 // are demanded, turn this into an unsigned shift right. 1632 if (Known.Zero[BitWidth - ShAmt - 1] || 1633 DemandedBits.countLeadingZeros() >= ShAmt) { 1634 SDNodeFlags Flags; 1635 Flags.setExact(Op->getFlags().hasExact()); 1636 return TLO.CombineTo( 1637 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1638 } 1639 1640 int Log2 = DemandedBits.exactLogBase2(); 1641 if (Log2 >= 0) { 1642 // The bit must come from the sign. 1643 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1644 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1645 } 1646 1647 if (Known.One[BitWidth - ShAmt - 1]) 1648 // New bits are known one. 1649 Known.One.setHighBits(ShAmt); 1650 1651 // Attempt to avoid multi-use ops if we don't need anything from them. 1652 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1653 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1654 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1655 if (DemandedOp0) { 1656 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1657 return TLO.CombineTo(Op, NewOp); 1658 } 1659 } 1660 } 1661 break; 1662 } 1663 case ISD::FSHL: 1664 case ISD::FSHR: { 1665 SDValue Op0 = Op.getOperand(0); 1666 SDValue Op1 = Op.getOperand(1); 1667 SDValue Op2 = Op.getOperand(2); 1668 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1669 1670 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1671 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1672 1673 // For fshl, 0-shift returns the 1st arg. 1674 // For fshr, 0-shift returns the 2nd arg. 1675 if (Amt == 0) { 1676 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1677 Known, TLO, Depth + 1)) 1678 return true; 1679 break; 1680 } 1681 1682 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1683 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1684 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1685 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1686 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1687 Depth + 1)) 1688 return true; 1689 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1690 Depth + 1)) 1691 return true; 1692 1693 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1694 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1695 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1696 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1697 Known.One |= Known2.One; 1698 Known.Zero |= Known2.Zero; 1699 } 1700 1701 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1702 if (isPowerOf2_32(BitWidth)) { 1703 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1704 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1705 Known2, TLO, Depth + 1)) 1706 return true; 1707 } 1708 break; 1709 } 1710 case ISD::ROTL: 1711 case ISD::ROTR: { 1712 SDValue Op0 = Op.getOperand(0); 1713 SDValue Op1 = Op.getOperand(1); 1714 1715 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1716 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1717 return TLO.CombineTo(Op, Op0); 1718 1719 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1720 if (isPowerOf2_32(BitWidth)) { 1721 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1722 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1723 Depth + 1)) 1724 return true; 1725 } 1726 break; 1727 } 1728 case ISD::UMIN: { 1729 // Check if one arg is always less than (or equal) to the other arg. 1730 SDValue Op0 = Op.getOperand(0); 1731 SDValue Op1 = Op.getOperand(1); 1732 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1733 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1734 Known = KnownBits::umin(Known0, Known1); 1735 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1736 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1737 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1738 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1739 break; 1740 } 1741 case ISD::UMAX: { 1742 // Check if one arg is always greater than (or equal) to the other arg. 1743 SDValue Op0 = Op.getOperand(0); 1744 SDValue Op1 = Op.getOperand(1); 1745 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1746 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1747 Known = KnownBits::umax(Known0, Known1); 1748 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1749 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1750 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1751 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1752 break; 1753 } 1754 case ISD::BITREVERSE: { 1755 SDValue Src = Op.getOperand(0); 1756 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1757 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1758 Depth + 1)) 1759 return true; 1760 Known.One = Known2.One.reverseBits(); 1761 Known.Zero = Known2.Zero.reverseBits(); 1762 break; 1763 } 1764 case ISD::BSWAP: { 1765 SDValue Src = Op.getOperand(0); 1766 APInt DemandedSrcBits = DemandedBits.byteSwap(); 1767 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1768 Depth + 1)) 1769 return true; 1770 Known.One = Known2.One.byteSwap(); 1771 Known.Zero = Known2.Zero.byteSwap(); 1772 break; 1773 } 1774 case ISD::CTPOP: { 1775 // If only 1 bit is demanded, replace with PARITY as long as we're before 1776 // op legalization. 1777 // FIXME: Limit to scalars for now. 1778 if (DemandedBits.isOneValue() && !TLO.LegalOps && !VT.isVector()) 1779 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 1780 Op.getOperand(0))); 1781 1782 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1783 break; 1784 } 1785 case ISD::SIGN_EXTEND_INREG: { 1786 SDValue Op0 = Op.getOperand(0); 1787 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1788 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 1789 1790 // If we only care about the highest bit, don't bother shifting right. 1791 if (DemandedBits.isSignMask()) { 1792 unsigned NumSignBits = 1793 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1794 bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1; 1795 // However if the input is already sign extended we expect the sign 1796 // extension to be dropped altogether later and do not simplify. 1797 if (!AlreadySignExtended) { 1798 // Compute the correct shift amount type, which must be getShiftAmountTy 1799 // for scalar types after legalization. 1800 EVT ShiftAmtTy = VT; 1801 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1802 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1803 1804 SDValue ShiftAmt = 1805 TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy); 1806 return TLO.CombineTo(Op, 1807 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 1808 } 1809 } 1810 1811 // If none of the extended bits are demanded, eliminate the sextinreg. 1812 if (DemandedBits.getActiveBits() <= ExVTBits) 1813 return TLO.CombineTo(Op, Op0); 1814 1815 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 1816 1817 // Since the sign extended bits are demanded, we know that the sign 1818 // bit is demanded. 1819 InputDemandedBits.setBit(ExVTBits - 1); 1820 1821 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 1822 return true; 1823 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1824 1825 // If the sign bit of the input is known set or clear, then we know the 1826 // top bits of the result. 1827 1828 // If the input sign bit is known zero, convert this into a zero extension. 1829 if (Known.Zero[ExVTBits - 1]) 1830 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 1831 1832 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 1833 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 1834 Known.One.setBitsFrom(ExVTBits); 1835 Known.Zero &= Mask; 1836 } else { // Input sign bit unknown 1837 Known.Zero &= Mask; 1838 Known.One &= Mask; 1839 } 1840 break; 1841 } 1842 case ISD::BUILD_PAIR: { 1843 EVT HalfVT = Op.getOperand(0).getValueType(); 1844 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1845 1846 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1847 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1848 1849 KnownBits KnownLo, KnownHi; 1850 1851 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 1852 return true; 1853 1854 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 1855 return true; 1856 1857 Known.Zero = KnownLo.Zero.zext(BitWidth) | 1858 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 1859 1860 Known.One = KnownLo.One.zext(BitWidth) | 1861 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 1862 break; 1863 } 1864 case ISD::ZERO_EXTEND: 1865 case ISD::ZERO_EXTEND_VECTOR_INREG: { 1866 SDValue Src = Op.getOperand(0); 1867 EVT SrcVT = Src.getValueType(); 1868 unsigned InBits = SrcVT.getScalarSizeInBits(); 1869 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1870 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 1871 1872 // If none of the top bits are demanded, convert this into an any_extend. 1873 if (DemandedBits.getActiveBits() <= InBits) { 1874 // If we only need the non-extended bits of the bottom element 1875 // then we can just bitcast to the result. 1876 if (IsVecInReg && DemandedElts == 1 && 1877 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1878 TLO.DAG.getDataLayout().isLittleEndian()) 1879 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1880 1881 unsigned Opc = 1882 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1883 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1884 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1885 } 1886 1887 APInt InDemandedBits = DemandedBits.trunc(InBits); 1888 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1889 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1890 Depth + 1)) 1891 return true; 1892 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1893 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1894 Known = Known.zext(BitWidth); 1895 1896 // Attempt to avoid multi-use ops if we don't need anything from them. 1897 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1898 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1899 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1900 break; 1901 } 1902 case ISD::SIGN_EXTEND: 1903 case ISD::SIGN_EXTEND_VECTOR_INREG: { 1904 SDValue Src = Op.getOperand(0); 1905 EVT SrcVT = Src.getValueType(); 1906 unsigned InBits = SrcVT.getScalarSizeInBits(); 1907 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1908 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 1909 1910 // If none of the top bits are demanded, convert this into an any_extend. 1911 if (DemandedBits.getActiveBits() <= InBits) { 1912 // If we only need the non-extended bits of the bottom element 1913 // then we can just bitcast to the result. 1914 if (IsVecInReg && DemandedElts == 1 && 1915 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1916 TLO.DAG.getDataLayout().isLittleEndian()) 1917 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1918 1919 unsigned Opc = 1920 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1921 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1922 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1923 } 1924 1925 APInt InDemandedBits = DemandedBits.trunc(InBits); 1926 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1927 1928 // Since some of the sign extended bits are demanded, we know that the sign 1929 // bit is demanded. 1930 InDemandedBits.setBit(InBits - 1); 1931 1932 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1933 Depth + 1)) 1934 return true; 1935 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1936 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1937 1938 // If the sign bit is known one, the top bits match. 1939 Known = Known.sext(BitWidth); 1940 1941 // If the sign bit is known zero, convert this to a zero extend. 1942 if (Known.isNonNegative()) { 1943 unsigned Opc = 1944 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 1945 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1946 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1947 } 1948 1949 // Attempt to avoid multi-use ops if we don't need anything from them. 1950 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1951 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1952 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1953 break; 1954 } 1955 case ISD::ANY_EXTEND: 1956 case ISD::ANY_EXTEND_VECTOR_INREG: { 1957 SDValue Src = Op.getOperand(0); 1958 EVT SrcVT = Src.getValueType(); 1959 unsigned InBits = SrcVT.getScalarSizeInBits(); 1960 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1961 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 1962 1963 // If we only need the bottom element then we can just bitcast. 1964 // TODO: Handle ANY_EXTEND? 1965 if (IsVecInReg && DemandedElts == 1 && 1966 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1967 TLO.DAG.getDataLayout().isLittleEndian()) 1968 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1969 1970 APInt InDemandedBits = DemandedBits.trunc(InBits); 1971 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1972 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1973 Depth + 1)) 1974 return true; 1975 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1976 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1977 Known = Known.anyext(BitWidth); 1978 1979 // Attempt to avoid multi-use ops if we don't need anything from them. 1980 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1981 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1982 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1983 break; 1984 } 1985 case ISD::TRUNCATE: { 1986 SDValue Src = Op.getOperand(0); 1987 1988 // Simplify the input, using demanded bit information, and compute the known 1989 // zero/one bits live out. 1990 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 1991 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 1992 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 1993 Depth + 1)) 1994 return true; 1995 Known = Known.trunc(BitWidth); 1996 1997 // Attempt to avoid multi-use ops if we don't need anything from them. 1998 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1999 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2000 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2001 2002 // If the input is only used by this truncate, see if we can shrink it based 2003 // on the known demanded bits. 2004 if (Src.getNode()->hasOneUse()) { 2005 switch (Src.getOpcode()) { 2006 default: 2007 break; 2008 case ISD::SRL: 2009 // Shrink SRL by a constant if none of the high bits shifted in are 2010 // demanded. 2011 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2012 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2013 // undesirable. 2014 break; 2015 2016 const APInt *ShAmtC = 2017 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2018 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2019 break; 2020 uint64_t ShVal = ShAmtC->getZExtValue(); 2021 2022 APInt HighBits = 2023 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2024 HighBits.lshrInPlace(ShVal); 2025 HighBits = HighBits.trunc(BitWidth); 2026 2027 if (!(HighBits & DemandedBits)) { 2028 // None of the shifted in bits are needed. Add a truncate of the 2029 // shift input, then shift it. 2030 SDValue NewShAmt = TLO.DAG.getConstant( 2031 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2032 SDValue NewTrunc = 2033 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2034 return TLO.CombineTo( 2035 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2036 } 2037 break; 2038 } 2039 } 2040 2041 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2042 break; 2043 } 2044 case ISD::AssertZext: { 2045 // AssertZext demands all of the high bits, plus any of the low bits 2046 // demanded by its users. 2047 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2048 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2049 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2050 TLO, Depth + 1)) 2051 return true; 2052 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2053 2054 Known.Zero |= ~InMask; 2055 break; 2056 } 2057 case ISD::EXTRACT_VECTOR_ELT: { 2058 SDValue Src = Op.getOperand(0); 2059 SDValue Idx = Op.getOperand(1); 2060 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2061 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2062 2063 if (SrcEltCnt.isScalable()) 2064 return false; 2065 2066 // Demand the bits from every vector element without a constant index. 2067 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2068 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 2069 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2070 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2071 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2072 2073 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2074 // anything about the extended bits. 2075 APInt DemandedSrcBits = DemandedBits; 2076 if (BitWidth > EltBitWidth) 2077 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2078 2079 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2080 Depth + 1)) 2081 return true; 2082 2083 // Attempt to avoid multi-use ops if we don't need anything from them. 2084 if (!DemandedSrcBits.isAllOnesValue() || 2085 !DemandedSrcElts.isAllOnesValue()) { 2086 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2087 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2088 SDValue NewOp = 2089 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2090 return TLO.CombineTo(Op, NewOp); 2091 } 2092 } 2093 2094 Known = Known2; 2095 if (BitWidth > EltBitWidth) 2096 Known = Known.anyext(BitWidth); 2097 break; 2098 } 2099 case ISD::BITCAST: { 2100 SDValue Src = Op.getOperand(0); 2101 EVT SrcVT = Src.getValueType(); 2102 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2103 2104 // If this is an FP->Int bitcast and if the sign bit is the only 2105 // thing demanded, turn this into a FGETSIGN. 2106 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2107 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2108 SrcVT.isFloatingPoint()) { 2109 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2110 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2111 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2112 SrcVT != MVT::f128) { 2113 // Cannot eliminate/lower SHL for f128 yet. 2114 EVT Ty = OpVTLegal ? VT : MVT::i32; 2115 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2116 // place. We expect the SHL to be eliminated by other optimizations. 2117 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2118 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2119 if (!OpVTLegal && OpVTSizeInBits > 32) 2120 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2121 unsigned ShVal = Op.getValueSizeInBits() - 1; 2122 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2123 return TLO.CombineTo(Op, 2124 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2125 } 2126 } 2127 2128 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2129 // Demand the elt/bit if any of the original elts/bits are demanded. 2130 // TODO - bigendian once we have test coverage. 2131 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0 && 2132 TLO.DAG.getDataLayout().isLittleEndian()) { 2133 unsigned Scale = BitWidth / NumSrcEltBits; 2134 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2135 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2136 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2137 for (unsigned i = 0; i != Scale; ++i) { 2138 unsigned Offset = i * NumSrcEltBits; 2139 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 2140 if (!Sub.isNullValue()) { 2141 DemandedSrcBits |= Sub; 2142 for (unsigned j = 0; j != NumElts; ++j) 2143 if (DemandedElts[j]) 2144 DemandedSrcElts.setBit((j * Scale) + i); 2145 } 2146 } 2147 2148 APInt KnownSrcUndef, KnownSrcZero; 2149 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2150 KnownSrcZero, TLO, Depth + 1)) 2151 return true; 2152 2153 KnownBits KnownSrcBits; 2154 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2155 KnownSrcBits, TLO, Depth + 1)) 2156 return true; 2157 } else if ((NumSrcEltBits % BitWidth) == 0 && 2158 TLO.DAG.getDataLayout().isLittleEndian()) { 2159 unsigned Scale = NumSrcEltBits / BitWidth; 2160 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2161 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2162 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2163 for (unsigned i = 0; i != NumElts; ++i) 2164 if (DemandedElts[i]) { 2165 unsigned Offset = (i % Scale) * BitWidth; 2166 DemandedSrcBits.insertBits(DemandedBits, Offset); 2167 DemandedSrcElts.setBit(i / Scale); 2168 } 2169 2170 if (SrcVT.isVector()) { 2171 APInt KnownSrcUndef, KnownSrcZero; 2172 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2173 KnownSrcZero, TLO, Depth + 1)) 2174 return true; 2175 } 2176 2177 KnownBits KnownSrcBits; 2178 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2179 KnownSrcBits, TLO, Depth + 1)) 2180 return true; 2181 } 2182 2183 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2184 // recursive call where Known may be useful to the caller. 2185 if (Depth > 0) { 2186 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2187 return false; 2188 } 2189 break; 2190 } 2191 case ISD::ADD: 2192 case ISD::MUL: 2193 case ISD::SUB: { 2194 // Add, Sub, and Mul don't demand any bits in positions beyond that 2195 // of the highest bit demanded of them. 2196 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2197 SDNodeFlags Flags = Op.getNode()->getFlags(); 2198 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2199 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2200 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2201 Depth + 1) || 2202 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2203 Depth + 1) || 2204 // See if the operation should be performed at a smaller bit width. 2205 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2206 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2207 // Disable the nsw and nuw flags. We can no longer guarantee that we 2208 // won't wrap after simplification. 2209 Flags.setNoSignedWrap(false); 2210 Flags.setNoUnsignedWrap(false); 2211 SDValue NewOp = 2212 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2213 return TLO.CombineTo(Op, NewOp); 2214 } 2215 return true; 2216 } 2217 2218 // Attempt to avoid multi-use ops if we don't need anything from them. 2219 if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 2220 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2221 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2222 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2223 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2224 if (DemandedOp0 || DemandedOp1) { 2225 Flags.setNoSignedWrap(false); 2226 Flags.setNoUnsignedWrap(false); 2227 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2228 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2229 SDValue NewOp = 2230 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2231 return TLO.CombineTo(Op, NewOp); 2232 } 2233 } 2234 2235 // If we have a constant operand, we may be able to turn it into -1 if we 2236 // do not demand the high bits. This can make the constant smaller to 2237 // encode, allow more general folding, or match specialized instruction 2238 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2239 // is probably not useful (and could be detrimental). 2240 ConstantSDNode *C = isConstOrConstSplat(Op1); 2241 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2242 if (C && !C->isAllOnesValue() && !C->isOne() && 2243 (C->getAPIntValue() | HighMask).isAllOnesValue()) { 2244 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2245 // Disable the nsw and nuw flags. We can no longer guarantee that we 2246 // won't wrap after simplification. 2247 Flags.setNoSignedWrap(false); 2248 Flags.setNoUnsignedWrap(false); 2249 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2250 return TLO.CombineTo(Op, NewOp); 2251 } 2252 2253 LLVM_FALLTHROUGH; 2254 } 2255 default: 2256 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2257 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2258 Known, TLO, Depth)) 2259 return true; 2260 break; 2261 } 2262 2263 // Just use computeKnownBits to compute output bits. 2264 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2265 break; 2266 } 2267 2268 // If we know the value of all of the demanded bits, return this as a 2269 // constant. 2270 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2271 // Avoid folding to a constant if any OpaqueConstant is involved. 2272 const SDNode *N = Op.getNode(); 2273 for (SDNode *Op : 2274 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2276 if (C->isOpaque()) 2277 return false; 2278 } 2279 if (VT.isInteger()) 2280 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2281 if (VT.isFloatingPoint()) 2282 return TLO.CombineTo( 2283 Op, 2284 TLO.DAG.getConstantFP( 2285 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2286 } 2287 2288 return false; 2289 } 2290 2291 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2292 const APInt &DemandedElts, 2293 APInt &KnownUndef, 2294 APInt &KnownZero, 2295 DAGCombinerInfo &DCI) const { 2296 SelectionDAG &DAG = DCI.DAG; 2297 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2298 !DCI.isBeforeLegalizeOps()); 2299 2300 bool Simplified = 2301 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2302 if (Simplified) { 2303 DCI.AddToWorklist(Op.getNode()); 2304 DCI.CommitTargetLoweringOpt(TLO); 2305 } 2306 2307 return Simplified; 2308 } 2309 2310 /// Given a vector binary operation and known undefined elements for each input 2311 /// operand, compute whether each element of the output is undefined. 2312 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2313 const APInt &UndefOp0, 2314 const APInt &UndefOp1) { 2315 EVT VT = BO.getValueType(); 2316 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2317 "Vector binop only"); 2318 2319 EVT EltVT = VT.getVectorElementType(); 2320 unsigned NumElts = VT.getVectorNumElements(); 2321 assert(UndefOp0.getBitWidth() == NumElts && 2322 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2323 2324 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2325 const APInt &UndefVals) { 2326 if (UndefVals[Index]) 2327 return DAG.getUNDEF(EltVT); 2328 2329 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2330 // Try hard to make sure that the getNode() call is not creating temporary 2331 // nodes. Ignore opaque integers because they do not constant fold. 2332 SDValue Elt = BV->getOperand(Index); 2333 auto *C = dyn_cast<ConstantSDNode>(Elt); 2334 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2335 return Elt; 2336 } 2337 2338 return SDValue(); 2339 }; 2340 2341 APInt KnownUndef = APInt::getNullValue(NumElts); 2342 for (unsigned i = 0; i != NumElts; ++i) { 2343 // If both inputs for this element are either constant or undef and match 2344 // the element type, compute the constant/undef result for this element of 2345 // the vector. 2346 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2347 // not handle FP constants. The code within getNode() should be refactored 2348 // to avoid the danger of creating a bogus temporary node here. 2349 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2350 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2351 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2352 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2353 KnownUndef.setBit(i); 2354 } 2355 return KnownUndef; 2356 } 2357 2358 bool TargetLowering::SimplifyDemandedVectorElts( 2359 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2360 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2361 bool AssumeSingleUse) const { 2362 EVT VT = Op.getValueType(); 2363 unsigned Opcode = Op.getOpcode(); 2364 APInt DemandedElts = OriginalDemandedElts; 2365 unsigned NumElts = DemandedElts.getBitWidth(); 2366 assert(VT.isVector() && "Expected vector op"); 2367 2368 KnownUndef = KnownZero = APInt::getNullValue(NumElts); 2369 2370 // TODO: For now we assume we know nothing about scalable vectors. 2371 if (VT.isScalableVector()) 2372 return false; 2373 2374 assert(VT.getVectorNumElements() == NumElts && 2375 "Mask size mismatches value type element count!"); 2376 2377 // Undef operand. 2378 if (Op.isUndef()) { 2379 KnownUndef.setAllBits(); 2380 return false; 2381 } 2382 2383 // If Op has other users, assume that all elements are needed. 2384 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2385 DemandedElts.setAllBits(); 2386 2387 // Not demanding any elements from Op. 2388 if (DemandedElts == 0) { 2389 KnownUndef.setAllBits(); 2390 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2391 } 2392 2393 // Limit search depth. 2394 if (Depth >= SelectionDAG::MaxRecursionDepth) 2395 return false; 2396 2397 SDLoc DL(Op); 2398 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2399 2400 // Helper for demanding the specified elements and all the bits of both binary 2401 // operands. 2402 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2403 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2404 TLO.DAG, Depth + 1); 2405 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2406 TLO.DAG, Depth + 1); 2407 if (NewOp0 || NewOp1) { 2408 SDValue NewOp = TLO.DAG.getNode( 2409 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2410 return TLO.CombineTo(Op, NewOp); 2411 } 2412 return false; 2413 }; 2414 2415 switch (Opcode) { 2416 case ISD::SCALAR_TO_VECTOR: { 2417 if (!DemandedElts[0]) { 2418 KnownUndef.setAllBits(); 2419 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2420 } 2421 KnownUndef.setHighBits(NumElts - 1); 2422 break; 2423 } 2424 case ISD::BITCAST: { 2425 SDValue Src = Op.getOperand(0); 2426 EVT SrcVT = Src.getValueType(); 2427 2428 // We only handle vectors here. 2429 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2430 if (!SrcVT.isVector()) 2431 break; 2432 2433 // Fast handling of 'identity' bitcasts. 2434 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2435 if (NumSrcElts == NumElts) 2436 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2437 KnownZero, TLO, Depth + 1); 2438 2439 APInt SrcZero, SrcUndef; 2440 APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts); 2441 2442 // Bitcast from 'large element' src vector to 'small element' vector, we 2443 // must demand a source element if any DemandedElt maps to it. 2444 if ((NumElts % NumSrcElts) == 0) { 2445 unsigned Scale = NumElts / NumSrcElts; 2446 for (unsigned i = 0; i != NumElts; ++i) 2447 if (DemandedElts[i]) 2448 SrcDemandedElts.setBit(i / Scale); 2449 2450 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2451 TLO, Depth + 1)) 2452 return true; 2453 2454 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2455 // of the large element. 2456 // TODO - bigendian once we have test coverage. 2457 if (TLO.DAG.getDataLayout().isLittleEndian()) { 2458 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2459 APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits); 2460 for (unsigned i = 0; i != NumElts; ++i) 2461 if (DemandedElts[i]) { 2462 unsigned Ofs = (i % Scale) * EltSizeInBits; 2463 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2464 } 2465 2466 KnownBits Known; 2467 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2468 TLO, Depth + 1)) 2469 return true; 2470 } 2471 2472 // If the src element is zero/undef then all the output elements will be - 2473 // only demanded elements are guaranteed to be correct. 2474 for (unsigned i = 0; i != NumSrcElts; ++i) { 2475 if (SrcDemandedElts[i]) { 2476 if (SrcZero[i]) 2477 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2478 if (SrcUndef[i]) 2479 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2480 } 2481 } 2482 } 2483 2484 // Bitcast from 'small element' src vector to 'large element' vector, we 2485 // demand all smaller source elements covered by the larger demanded element 2486 // of this vector. 2487 if ((NumSrcElts % NumElts) == 0) { 2488 unsigned Scale = NumSrcElts / NumElts; 2489 for (unsigned i = 0; i != NumElts; ++i) 2490 if (DemandedElts[i]) 2491 SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale); 2492 2493 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2494 TLO, Depth + 1)) 2495 return true; 2496 2497 // If all the src elements covering an output element are zero/undef, then 2498 // the output element will be as well, assuming it was demanded. 2499 for (unsigned i = 0; i != NumElts; ++i) { 2500 if (DemandedElts[i]) { 2501 if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue()) 2502 KnownZero.setBit(i); 2503 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue()) 2504 KnownUndef.setBit(i); 2505 } 2506 } 2507 } 2508 break; 2509 } 2510 case ISD::BUILD_VECTOR: { 2511 // Check all elements and simplify any unused elements with UNDEF. 2512 if (!DemandedElts.isAllOnesValue()) { 2513 // Don't simplify BROADCASTS. 2514 if (llvm::any_of(Op->op_values(), 2515 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2516 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2517 bool Updated = false; 2518 for (unsigned i = 0; i != NumElts; ++i) { 2519 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2520 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2521 KnownUndef.setBit(i); 2522 Updated = true; 2523 } 2524 } 2525 if (Updated) 2526 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2527 } 2528 } 2529 for (unsigned i = 0; i != NumElts; ++i) { 2530 SDValue SrcOp = Op.getOperand(i); 2531 if (SrcOp.isUndef()) { 2532 KnownUndef.setBit(i); 2533 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2534 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2535 KnownZero.setBit(i); 2536 } 2537 } 2538 break; 2539 } 2540 case ISD::CONCAT_VECTORS: { 2541 EVT SubVT = Op.getOperand(0).getValueType(); 2542 unsigned NumSubVecs = Op.getNumOperands(); 2543 unsigned NumSubElts = SubVT.getVectorNumElements(); 2544 for (unsigned i = 0; i != NumSubVecs; ++i) { 2545 SDValue SubOp = Op.getOperand(i); 2546 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2547 APInt SubUndef, SubZero; 2548 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2549 Depth + 1)) 2550 return true; 2551 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2552 KnownZero.insertBits(SubZero, i * NumSubElts); 2553 } 2554 break; 2555 } 2556 case ISD::INSERT_SUBVECTOR: { 2557 // Demand any elements from the subvector and the remainder from the src its 2558 // inserted into. 2559 SDValue Src = Op.getOperand(0); 2560 SDValue Sub = Op.getOperand(1); 2561 uint64_t Idx = Op.getConstantOperandVal(2); 2562 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2563 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2564 APInt DemandedSrcElts = DemandedElts; 2565 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2566 2567 APInt SubUndef, SubZero; 2568 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2569 Depth + 1)) 2570 return true; 2571 2572 // If none of the src operand elements are demanded, replace it with undef. 2573 if (!DemandedSrcElts && !Src.isUndef()) 2574 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2575 TLO.DAG.getUNDEF(VT), Sub, 2576 Op.getOperand(2))); 2577 2578 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2579 TLO, Depth + 1)) 2580 return true; 2581 KnownUndef.insertBits(SubUndef, Idx); 2582 KnownZero.insertBits(SubZero, Idx); 2583 2584 // Attempt to avoid multi-use ops if we don't need anything from them. 2585 if (!DemandedSrcElts.isAllOnesValue() || 2586 !DemandedSubElts.isAllOnesValue()) { 2587 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2588 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2589 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2590 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2591 if (NewSrc || NewSub) { 2592 NewSrc = NewSrc ? NewSrc : Src; 2593 NewSub = NewSub ? NewSub : Sub; 2594 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2595 NewSub, Op.getOperand(2)); 2596 return TLO.CombineTo(Op, NewOp); 2597 } 2598 } 2599 break; 2600 } 2601 case ISD::EXTRACT_SUBVECTOR: { 2602 // Offset the demanded elts by the subvector index. 2603 SDValue Src = Op.getOperand(0); 2604 if (Src.getValueType().isScalableVector()) 2605 break; 2606 uint64_t Idx = Op.getConstantOperandVal(1); 2607 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2608 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2609 2610 APInt SrcUndef, SrcZero; 2611 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2612 Depth + 1)) 2613 return true; 2614 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2615 KnownZero = SrcZero.extractBits(NumElts, Idx); 2616 2617 // Attempt to avoid multi-use ops if we don't need anything from them. 2618 if (!DemandedElts.isAllOnesValue()) { 2619 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2620 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2621 if (NewSrc) { 2622 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2623 Op.getOperand(1)); 2624 return TLO.CombineTo(Op, NewOp); 2625 } 2626 } 2627 break; 2628 } 2629 case ISD::INSERT_VECTOR_ELT: { 2630 SDValue Vec = Op.getOperand(0); 2631 SDValue Scl = Op.getOperand(1); 2632 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2633 2634 // For a legal, constant insertion index, if we don't need this insertion 2635 // then strip it, else remove it from the demanded elts. 2636 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2637 unsigned Idx = CIdx->getZExtValue(); 2638 if (!DemandedElts[Idx]) 2639 return TLO.CombineTo(Op, Vec); 2640 2641 APInt DemandedVecElts(DemandedElts); 2642 DemandedVecElts.clearBit(Idx); 2643 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2644 KnownZero, TLO, Depth + 1)) 2645 return true; 2646 2647 KnownUndef.setBitVal(Idx, Scl.isUndef()); 2648 2649 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 2650 break; 2651 } 2652 2653 APInt VecUndef, VecZero; 2654 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2655 Depth + 1)) 2656 return true; 2657 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2658 break; 2659 } 2660 case ISD::VSELECT: { 2661 // Try to transform the select condition based on the current demanded 2662 // elements. 2663 // TODO: If a condition element is undef, we can choose from one arm of the 2664 // select (and if one arm is undef, then we can propagate that to the 2665 // result). 2666 // TODO - add support for constant vselect masks (see IR version of this). 2667 APInt UnusedUndef, UnusedZero; 2668 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 2669 UnusedZero, TLO, Depth + 1)) 2670 return true; 2671 2672 // See if we can simplify either vselect operand. 2673 APInt DemandedLHS(DemandedElts); 2674 APInt DemandedRHS(DemandedElts); 2675 APInt UndefLHS, ZeroLHS; 2676 APInt UndefRHS, ZeroRHS; 2677 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 2678 ZeroLHS, TLO, Depth + 1)) 2679 return true; 2680 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 2681 ZeroRHS, TLO, Depth + 1)) 2682 return true; 2683 2684 KnownUndef = UndefLHS & UndefRHS; 2685 KnownZero = ZeroLHS & ZeroRHS; 2686 break; 2687 } 2688 case ISD::VECTOR_SHUFFLE: { 2689 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 2690 2691 // Collect demanded elements from shuffle operands.. 2692 APInt DemandedLHS(NumElts, 0); 2693 APInt DemandedRHS(NumElts, 0); 2694 for (unsigned i = 0; i != NumElts; ++i) { 2695 int M = ShuffleMask[i]; 2696 if (M < 0 || !DemandedElts[i]) 2697 continue; 2698 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 2699 if (M < (int)NumElts) 2700 DemandedLHS.setBit(M); 2701 else 2702 DemandedRHS.setBit(M - NumElts); 2703 } 2704 2705 // See if we can simplify either shuffle operand. 2706 APInt UndefLHS, ZeroLHS; 2707 APInt UndefRHS, ZeroRHS; 2708 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 2709 ZeroLHS, TLO, Depth + 1)) 2710 return true; 2711 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 2712 ZeroRHS, TLO, Depth + 1)) 2713 return true; 2714 2715 // Simplify mask using undef elements from LHS/RHS. 2716 bool Updated = false; 2717 bool IdentityLHS = true, IdentityRHS = true; 2718 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 2719 for (unsigned i = 0; i != NumElts; ++i) { 2720 int &M = NewMask[i]; 2721 if (M < 0) 2722 continue; 2723 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 2724 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 2725 Updated = true; 2726 M = -1; 2727 } 2728 IdentityLHS &= (M < 0) || (M == (int)i); 2729 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 2730 } 2731 2732 // Update legal shuffle masks based on demanded elements if it won't reduce 2733 // to Identity which can cause premature removal of the shuffle mask. 2734 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 2735 SDValue LegalShuffle = 2736 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 2737 NewMask, TLO.DAG); 2738 if (LegalShuffle) 2739 return TLO.CombineTo(Op, LegalShuffle); 2740 } 2741 2742 // Propagate undef/zero elements from LHS/RHS. 2743 for (unsigned i = 0; i != NumElts; ++i) { 2744 int M = ShuffleMask[i]; 2745 if (M < 0) { 2746 KnownUndef.setBit(i); 2747 } else if (M < (int)NumElts) { 2748 if (UndefLHS[M]) 2749 KnownUndef.setBit(i); 2750 if (ZeroLHS[M]) 2751 KnownZero.setBit(i); 2752 } else { 2753 if (UndefRHS[M - NumElts]) 2754 KnownUndef.setBit(i); 2755 if (ZeroRHS[M - NumElts]) 2756 KnownZero.setBit(i); 2757 } 2758 } 2759 break; 2760 } 2761 case ISD::ANY_EXTEND_VECTOR_INREG: 2762 case ISD::SIGN_EXTEND_VECTOR_INREG: 2763 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2764 APInt SrcUndef, SrcZero; 2765 SDValue Src = Op.getOperand(0); 2766 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2767 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2768 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2769 Depth + 1)) 2770 return true; 2771 KnownZero = SrcZero.zextOrTrunc(NumElts); 2772 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 2773 2774 if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 2775 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 2776 DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) { 2777 // aext - if we just need the bottom element then we can bitcast. 2778 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2779 } 2780 2781 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 2782 // zext(undef) upper bits are guaranteed to be zero. 2783 if (DemandedElts.isSubsetOf(KnownUndef)) 2784 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2785 KnownUndef.clearAllBits(); 2786 } 2787 break; 2788 } 2789 2790 // TODO: There are more binop opcodes that could be handled here - MIN, 2791 // MAX, saturated math, etc. 2792 case ISD::OR: 2793 case ISD::XOR: 2794 case ISD::ADD: 2795 case ISD::SUB: 2796 case ISD::FADD: 2797 case ISD::FSUB: 2798 case ISD::FMUL: 2799 case ISD::FDIV: 2800 case ISD::FREM: { 2801 SDValue Op0 = Op.getOperand(0); 2802 SDValue Op1 = Op.getOperand(1); 2803 2804 APInt UndefRHS, ZeroRHS; 2805 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2806 Depth + 1)) 2807 return true; 2808 APInt UndefLHS, ZeroLHS; 2809 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2810 Depth + 1)) 2811 return true; 2812 2813 KnownZero = ZeroLHS & ZeroRHS; 2814 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 2815 2816 // Attempt to avoid multi-use ops if we don't need anything from them. 2817 // TODO - use KnownUndef to relax the demandedelts? 2818 if (!DemandedElts.isAllOnesValue()) 2819 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2820 return true; 2821 break; 2822 } 2823 case ISD::SHL: 2824 case ISD::SRL: 2825 case ISD::SRA: 2826 case ISD::ROTL: 2827 case ISD::ROTR: { 2828 SDValue Op0 = Op.getOperand(0); 2829 SDValue Op1 = Op.getOperand(1); 2830 2831 APInt UndefRHS, ZeroRHS; 2832 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2833 Depth + 1)) 2834 return true; 2835 APInt UndefLHS, ZeroLHS; 2836 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2837 Depth + 1)) 2838 return true; 2839 2840 KnownZero = ZeroLHS; 2841 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 2842 2843 // Attempt to avoid multi-use ops if we don't need anything from them. 2844 // TODO - use KnownUndef to relax the demandedelts? 2845 if (!DemandedElts.isAllOnesValue()) 2846 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2847 return true; 2848 break; 2849 } 2850 case ISD::MUL: 2851 case ISD::AND: { 2852 SDValue Op0 = Op.getOperand(0); 2853 SDValue Op1 = Op.getOperand(1); 2854 2855 APInt SrcUndef, SrcZero; 2856 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 2857 Depth + 1)) 2858 return true; 2859 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 2860 TLO, Depth + 1)) 2861 return true; 2862 2863 // If either side has a zero element, then the result element is zero, even 2864 // if the other is an UNDEF. 2865 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 2866 // and then handle 'and' nodes with the rest of the binop opcodes. 2867 KnownZero |= SrcZero; 2868 KnownUndef &= SrcUndef; 2869 KnownUndef &= ~KnownZero; 2870 2871 // Attempt to avoid multi-use ops if we don't need anything from them. 2872 // TODO - use KnownUndef to relax the demandedelts? 2873 if (!DemandedElts.isAllOnesValue()) 2874 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2875 return true; 2876 break; 2877 } 2878 case ISD::TRUNCATE: 2879 case ISD::SIGN_EXTEND: 2880 case ISD::ZERO_EXTEND: 2881 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 2882 KnownZero, TLO, Depth + 1)) 2883 return true; 2884 2885 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 2886 // zext(undef) upper bits are guaranteed to be zero. 2887 if (DemandedElts.isSubsetOf(KnownUndef)) 2888 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2889 KnownUndef.clearAllBits(); 2890 } 2891 break; 2892 default: { 2893 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2894 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 2895 KnownZero, TLO, Depth)) 2896 return true; 2897 } else { 2898 KnownBits Known; 2899 APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits); 2900 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 2901 TLO, Depth, AssumeSingleUse)) 2902 return true; 2903 } 2904 break; 2905 } 2906 } 2907 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 2908 2909 // Constant fold all undef cases. 2910 // TODO: Handle zero cases as well. 2911 if (DemandedElts.isSubsetOf(KnownUndef)) 2912 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2913 2914 return false; 2915 } 2916 2917 /// Determine which of the bits specified in Mask are known to be either zero or 2918 /// one and return them in the Known. 2919 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 2920 KnownBits &Known, 2921 const APInt &DemandedElts, 2922 const SelectionDAG &DAG, 2923 unsigned Depth) const { 2924 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2925 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2926 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2927 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2928 "Should use MaskedValueIsZero if you don't know whether Op" 2929 " is a target node!"); 2930 Known.resetAll(); 2931 } 2932 2933 void TargetLowering::computeKnownBitsForTargetInstr( 2934 GISelKnownBits &Analysis, Register R, KnownBits &Known, 2935 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 2936 unsigned Depth) const { 2937 Known.resetAll(); 2938 } 2939 2940 void TargetLowering::computeKnownBitsForFrameIndex( 2941 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 2942 // The low bits are known zero if the pointer is aligned. 2943 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 2944 } 2945 2946 Align TargetLowering::computeKnownAlignForTargetInstr( 2947 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 2948 unsigned Depth) const { 2949 return Align(1); 2950 } 2951 2952 /// This method can be implemented by targets that want to expose additional 2953 /// information about sign bits to the DAG Combiner. 2954 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 2955 const APInt &, 2956 const SelectionDAG &, 2957 unsigned Depth) const { 2958 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2959 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2960 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2961 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2962 "Should use ComputeNumSignBits if you don't know whether Op" 2963 " is a target node!"); 2964 return 1; 2965 } 2966 2967 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 2968 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 2969 const MachineRegisterInfo &MRI, unsigned Depth) const { 2970 return 1; 2971 } 2972 2973 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 2974 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 2975 TargetLoweringOpt &TLO, unsigned Depth) const { 2976 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2977 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2978 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2979 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2980 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 2981 " is a target node!"); 2982 return false; 2983 } 2984 2985 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 2986 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2987 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 2988 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2989 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2990 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2991 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2992 "Should use SimplifyDemandedBits if you don't know whether Op" 2993 " is a target node!"); 2994 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 2995 return false; 2996 } 2997 2998 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 2999 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3000 SelectionDAG &DAG, unsigned Depth) const { 3001 assert( 3002 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3003 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3004 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3005 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3006 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3007 " is a target node!"); 3008 return SDValue(); 3009 } 3010 3011 SDValue 3012 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3013 SDValue N1, MutableArrayRef<int> Mask, 3014 SelectionDAG &DAG) const { 3015 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3016 if (!LegalMask) { 3017 std::swap(N0, N1); 3018 ShuffleVectorSDNode::commuteMask(Mask); 3019 LegalMask = isShuffleMaskLegal(Mask, VT); 3020 } 3021 3022 if (!LegalMask) 3023 return SDValue(); 3024 3025 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3026 } 3027 3028 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3029 return nullptr; 3030 } 3031 3032 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3033 const SelectionDAG &DAG, 3034 bool SNaN, 3035 unsigned Depth) const { 3036 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3037 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3038 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3039 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3040 "Should use isKnownNeverNaN if you don't know whether Op" 3041 " is a target node!"); 3042 return false; 3043 } 3044 3045 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3046 // work with truncating build vectors and vectors with elements of less than 3047 // 8 bits. 3048 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 3049 if (!N) 3050 return false; 3051 3052 APInt CVal; 3053 if (auto *CN = dyn_cast<ConstantSDNode>(N)) { 3054 CVal = CN->getAPIntValue(); 3055 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) { 3056 auto *CN = BV->getConstantSplatNode(); 3057 if (!CN) 3058 return false; 3059 3060 // If this is a truncating build vector, truncate the splat value. 3061 // Otherwise, we may fail to match the expected values below. 3062 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits(); 3063 CVal = CN->getAPIntValue(); 3064 if (BVEltWidth < CVal.getBitWidth()) 3065 CVal = CVal.trunc(BVEltWidth); 3066 } else { 3067 return false; 3068 } 3069 3070 switch (getBooleanContents(N->getValueType(0))) { 3071 case UndefinedBooleanContent: 3072 return CVal[0]; 3073 case ZeroOrOneBooleanContent: 3074 return CVal.isOneValue(); 3075 case ZeroOrNegativeOneBooleanContent: 3076 return CVal.isAllOnesValue(); 3077 } 3078 3079 llvm_unreachable("Invalid boolean contents"); 3080 } 3081 3082 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 3083 if (!N) 3084 return false; 3085 3086 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3087 if (!CN) { 3088 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3089 if (!BV) 3090 return false; 3091 3092 // Only interested in constant splats, we don't care about undef 3093 // elements in identifying boolean constants and getConstantSplatNode 3094 // returns NULL if all ops are undef; 3095 CN = BV->getConstantSplatNode(); 3096 if (!CN) 3097 return false; 3098 } 3099 3100 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3101 return !CN->getAPIntValue()[0]; 3102 3103 return CN->isNullValue(); 3104 } 3105 3106 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3107 bool SExt) const { 3108 if (VT == MVT::i1) 3109 return N->isOne(); 3110 3111 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3112 switch (Cnt) { 3113 case TargetLowering::ZeroOrOneBooleanContent: 3114 // An extended value of 1 is always true, unless its original type is i1, 3115 // in which case it will be sign extended to -1. 3116 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3117 case TargetLowering::UndefinedBooleanContent: 3118 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3119 return N->isAllOnesValue() && SExt; 3120 } 3121 llvm_unreachable("Unexpected enumeration."); 3122 } 3123 3124 /// This helper function of SimplifySetCC tries to optimize the comparison when 3125 /// either operand of the SetCC node is a bitwise-and instruction. 3126 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3127 ISD::CondCode Cond, const SDLoc &DL, 3128 DAGCombinerInfo &DCI) const { 3129 // Match these patterns in any of their permutations: 3130 // (X & Y) == Y 3131 // (X & Y) != Y 3132 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3133 std::swap(N0, N1); 3134 3135 EVT OpVT = N0.getValueType(); 3136 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3137 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3138 return SDValue(); 3139 3140 SDValue X, Y; 3141 if (N0.getOperand(0) == N1) { 3142 X = N0.getOperand(1); 3143 Y = N0.getOperand(0); 3144 } else if (N0.getOperand(1) == N1) { 3145 X = N0.getOperand(0); 3146 Y = N0.getOperand(1); 3147 } else { 3148 return SDValue(); 3149 } 3150 3151 SelectionDAG &DAG = DCI.DAG; 3152 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3153 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3154 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3155 // Note that where Y is variable and is known to have at most one bit set 3156 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3157 // equivalent when Y == 0. 3158 assert(OpVT.isInteger()); 3159 Cond = ISD::getSetCCInverse(Cond, OpVT); 3160 if (DCI.isBeforeLegalizeOps() || 3161 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3162 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3163 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3164 // If the target supports an 'and-not' or 'and-complement' logic operation, 3165 // try to use that to make a comparison operation more efficient. 3166 // But don't do this transform if the mask is a single bit because there are 3167 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3168 // 'rlwinm' on PPC). 3169 3170 // Bail out if the compare operand that we want to turn into a zero is 3171 // already a zero (otherwise, infinite loop). 3172 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3173 if (YConst && YConst->isNullValue()) 3174 return SDValue(); 3175 3176 // Transform this into: ~X & Y == 0. 3177 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3178 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3179 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3180 } 3181 3182 return SDValue(); 3183 } 3184 3185 /// There are multiple IR patterns that could be checking whether certain 3186 /// truncation of a signed number would be lossy or not. The pattern which is 3187 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3188 /// We are looking for the following pattern: (KeptBits is a constant) 3189 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3190 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3191 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3192 /// We will unfold it into the natural trunc+sext pattern: 3193 /// ((%x << C) a>> C) dstcond %x 3194 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3195 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3196 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3197 const SDLoc &DL) const { 3198 // We must be comparing with a constant. 3199 ConstantSDNode *C1; 3200 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3201 return SDValue(); 3202 3203 // N0 should be: add %x, (1 << (KeptBits-1)) 3204 if (N0->getOpcode() != ISD::ADD) 3205 return SDValue(); 3206 3207 // And we must be 'add'ing a constant. 3208 ConstantSDNode *C01; 3209 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3210 return SDValue(); 3211 3212 SDValue X = N0->getOperand(0); 3213 EVT XVT = X.getValueType(); 3214 3215 // Validate constants ... 3216 3217 APInt I1 = C1->getAPIntValue(); 3218 3219 ISD::CondCode NewCond; 3220 if (Cond == ISD::CondCode::SETULT) { 3221 NewCond = ISD::CondCode::SETEQ; 3222 } else if (Cond == ISD::CondCode::SETULE) { 3223 NewCond = ISD::CondCode::SETEQ; 3224 // But need to 'canonicalize' the constant. 3225 I1 += 1; 3226 } else if (Cond == ISD::CondCode::SETUGT) { 3227 NewCond = ISD::CondCode::SETNE; 3228 // But need to 'canonicalize' the constant. 3229 I1 += 1; 3230 } else if (Cond == ISD::CondCode::SETUGE) { 3231 NewCond = ISD::CondCode::SETNE; 3232 } else 3233 return SDValue(); 3234 3235 APInt I01 = C01->getAPIntValue(); 3236 3237 auto checkConstants = [&I1, &I01]() -> bool { 3238 // Both of them must be power-of-two, and the constant from setcc is bigger. 3239 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3240 }; 3241 3242 if (checkConstants()) { 3243 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3244 } else { 3245 // What if we invert constants? (and the target predicate) 3246 I1.negate(); 3247 I01.negate(); 3248 assert(XVT.isInteger()); 3249 NewCond = getSetCCInverse(NewCond, XVT); 3250 if (!checkConstants()) 3251 return SDValue(); 3252 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3253 } 3254 3255 // They are power-of-two, so which bit is set? 3256 const unsigned KeptBits = I1.logBase2(); 3257 const unsigned KeptBitsMinusOne = I01.logBase2(); 3258 3259 // Magic! 3260 if (KeptBits != (KeptBitsMinusOne + 1)) 3261 return SDValue(); 3262 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3263 3264 // We don't want to do this in every single case. 3265 SelectionDAG &DAG = DCI.DAG; 3266 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3267 XVT, KeptBits)) 3268 return SDValue(); 3269 3270 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3271 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3272 3273 // Unfold into: ((%x << C) a>> C) cond %x 3274 // Where 'cond' will be either 'eq' or 'ne'. 3275 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3276 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3277 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3278 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3279 3280 return T2; 3281 } 3282 3283 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3284 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3285 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3286 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3287 assert(isConstOrConstSplat(N1C) && 3288 isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() && 3289 "Should be a comparison with 0."); 3290 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3291 "Valid only for [in]equality comparisons."); 3292 3293 unsigned NewShiftOpcode; 3294 SDValue X, C, Y; 3295 3296 SelectionDAG &DAG = DCI.DAG; 3297 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3298 3299 // Look for '(C l>>/<< Y)'. 3300 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3301 // The shift should be one-use. 3302 if (!V.hasOneUse()) 3303 return false; 3304 unsigned OldShiftOpcode = V.getOpcode(); 3305 switch (OldShiftOpcode) { 3306 case ISD::SHL: 3307 NewShiftOpcode = ISD::SRL; 3308 break; 3309 case ISD::SRL: 3310 NewShiftOpcode = ISD::SHL; 3311 break; 3312 default: 3313 return false; // must be a logical shift. 3314 } 3315 // We should be shifting a constant. 3316 // FIXME: best to use isConstantOrConstantVector(). 3317 C = V.getOperand(0); 3318 ConstantSDNode *CC = 3319 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3320 if (!CC) 3321 return false; 3322 Y = V.getOperand(1); 3323 3324 ConstantSDNode *XC = 3325 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3326 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3327 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3328 }; 3329 3330 // LHS of comparison should be an one-use 'and'. 3331 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3332 return SDValue(); 3333 3334 X = N0.getOperand(0); 3335 SDValue Mask = N0.getOperand(1); 3336 3337 // 'and' is commutative! 3338 if (!Match(Mask)) { 3339 std::swap(X, Mask); 3340 if (!Match(Mask)) 3341 return SDValue(); 3342 } 3343 3344 EVT VT = X.getValueType(); 3345 3346 // Produce: 3347 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3348 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3349 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3350 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3351 return T2; 3352 } 3353 3354 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3355 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3356 /// handle the commuted versions of these patterns. 3357 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3358 ISD::CondCode Cond, const SDLoc &DL, 3359 DAGCombinerInfo &DCI) const { 3360 unsigned BOpcode = N0.getOpcode(); 3361 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3362 "Unexpected binop"); 3363 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3364 3365 // (X + Y) == X --> Y == 0 3366 // (X - Y) == X --> Y == 0 3367 // (X ^ Y) == X --> Y == 0 3368 SelectionDAG &DAG = DCI.DAG; 3369 EVT OpVT = N0.getValueType(); 3370 SDValue X = N0.getOperand(0); 3371 SDValue Y = N0.getOperand(1); 3372 if (X == N1) 3373 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3374 3375 if (Y != N1) 3376 return SDValue(); 3377 3378 // (X + Y) == Y --> X == 0 3379 // (X ^ Y) == Y --> X == 0 3380 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3381 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3382 3383 // The shift would not be valid if the operands are boolean (i1). 3384 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3385 return SDValue(); 3386 3387 // (X - Y) == Y --> X == Y << 1 3388 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3389 !DCI.isBeforeLegalize()); 3390 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3391 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3392 if (!DCI.isCalledByLegalizer()) 3393 DCI.AddToWorklist(YShl1.getNode()); 3394 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3395 } 3396 3397 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3398 SDValue N0, const APInt &C1, 3399 ISD::CondCode Cond, const SDLoc &dl, 3400 SelectionDAG &DAG) { 3401 // Look through truncs that don't change the value of a ctpop. 3402 // FIXME: Add vector support? Need to be careful with setcc result type below. 3403 SDValue CTPOP = N0; 3404 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3405 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3406 CTPOP = N0.getOperand(0); 3407 3408 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3409 return SDValue(); 3410 3411 EVT CTVT = CTPOP.getValueType(); 3412 SDValue CTOp = CTPOP.getOperand(0); 3413 3414 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3415 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3416 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3417 return SDValue(); 3418 3419 // (ctpop x) u< 2 -> (x & x-1) == 0 3420 // (ctpop x) u> 1 -> (x & x-1) != 0 3421 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3422 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3423 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3424 return SDValue(); 3425 if (C1 == 0 && (Cond == ISD::SETULT)) 3426 return SDValue(); // This is handled elsewhere. 3427 3428 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3429 3430 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3431 SDValue Result = CTOp; 3432 for (unsigned i = 0; i < Passes; i++) { 3433 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3434 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3435 } 3436 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3437 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3438 } 3439 3440 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3441 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3442 // For scalars, keep CTPOP if it is legal or custom. 3443 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3444 return SDValue(); 3445 // This is based on X86's custom lowering for CTPOP which produces more 3446 // instructions than the expansion here. 3447 3448 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3449 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3450 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3451 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3452 assert(CTVT.isInteger()); 3453 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3454 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3455 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3456 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3457 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3458 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3459 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3460 } 3461 3462 return SDValue(); 3463 } 3464 3465 /// Try to simplify a setcc built with the specified operands and cc. If it is 3466 /// unable to simplify it, return a null SDValue. 3467 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3468 ISD::CondCode Cond, bool foldBooleans, 3469 DAGCombinerInfo &DCI, 3470 const SDLoc &dl) const { 3471 SelectionDAG &DAG = DCI.DAG; 3472 const DataLayout &Layout = DAG.getDataLayout(); 3473 EVT OpVT = N0.getValueType(); 3474 3475 // Constant fold or commute setcc. 3476 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 3477 return Fold; 3478 3479 // Ensure that the constant occurs on the RHS and fold constant comparisons. 3480 // TODO: Handle non-splat vector constants. All undef causes trouble. 3481 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 3482 // infinite loop here when we encounter one. 3483 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 3484 if (isConstOrConstSplat(N0) && 3485 (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) && 3486 (DCI.isBeforeLegalizeOps() || 3487 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 3488 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3489 3490 // If we have a subtract with the same 2 non-constant operands as this setcc 3491 // -- but in reverse order -- then try to commute the operands of this setcc 3492 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 3493 // instruction on some targets. 3494 if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) && 3495 (DCI.isBeforeLegalizeOps() || 3496 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 3497 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 3498 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 3499 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3500 3501 if (auto *N1C = isConstOrConstSplat(N1)) { 3502 const APInt &C1 = N1C->getAPIntValue(); 3503 3504 // Optimize some CTPOP cases. 3505 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 3506 return V; 3507 3508 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 3509 // equality comparison, then we're just comparing whether X itself is 3510 // zero. 3511 if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) && 3512 N0.getOperand(0).getOpcode() == ISD::CTLZ && 3513 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 3514 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 3515 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3516 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 3517 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 3518 // (srl (ctlz x), 5) == 0 -> X != 0 3519 // (srl (ctlz x), 5) != 1 -> X != 0 3520 Cond = ISD::SETNE; 3521 } else { 3522 // (srl (ctlz x), 5) != 0 -> X == 0 3523 // (srl (ctlz x), 5) == 1 -> X == 0 3524 Cond = ISD::SETEQ; 3525 } 3526 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 3527 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 3528 Cond); 3529 } 3530 } 3531 } 3532 } 3533 3534 // FIXME: Support vectors. 3535 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 3536 const APInt &C1 = N1C->getAPIntValue(); 3537 3538 // (zext x) == C --> x == (trunc C) 3539 // (sext x) == C --> x == (trunc C) 3540 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3541 DCI.isBeforeLegalize() && N0->hasOneUse()) { 3542 unsigned MinBits = N0.getValueSizeInBits(); 3543 SDValue PreExt; 3544 bool Signed = false; 3545 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 3546 // ZExt 3547 MinBits = N0->getOperand(0).getValueSizeInBits(); 3548 PreExt = N0->getOperand(0); 3549 } else if (N0->getOpcode() == ISD::AND) { 3550 // DAGCombine turns costly ZExts into ANDs 3551 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 3552 if ((C->getAPIntValue()+1).isPowerOf2()) { 3553 MinBits = C->getAPIntValue().countTrailingOnes(); 3554 PreExt = N0->getOperand(0); 3555 } 3556 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 3557 // SExt 3558 MinBits = N0->getOperand(0).getValueSizeInBits(); 3559 PreExt = N0->getOperand(0); 3560 Signed = true; 3561 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 3562 // ZEXTLOAD / SEXTLOAD 3563 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 3564 MinBits = LN0->getMemoryVT().getSizeInBits(); 3565 PreExt = N0; 3566 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 3567 Signed = true; 3568 MinBits = LN0->getMemoryVT().getSizeInBits(); 3569 PreExt = N0; 3570 } 3571 } 3572 3573 // Figure out how many bits we need to preserve this constant. 3574 unsigned ReqdBits = Signed ? 3575 C1.getBitWidth() - C1.getNumSignBits() + 1 : 3576 C1.getActiveBits(); 3577 3578 // Make sure we're not losing bits from the constant. 3579 if (MinBits > 0 && 3580 MinBits < C1.getBitWidth() && 3581 MinBits >= ReqdBits) { 3582 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 3583 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 3584 // Will get folded away. 3585 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 3586 if (MinBits == 1 && C1 == 1) 3587 // Invert the condition. 3588 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 3589 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3590 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 3591 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 3592 } 3593 3594 // If truncating the setcc operands is not desirable, we can still 3595 // simplify the expression in some cases: 3596 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 3597 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 3598 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 3599 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 3600 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 3601 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 3602 SDValue TopSetCC = N0->getOperand(0); 3603 unsigned N0Opc = N0->getOpcode(); 3604 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 3605 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 3606 TopSetCC.getOpcode() == ISD::SETCC && 3607 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 3608 (isConstFalseVal(N1C) || 3609 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 3610 3611 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 3612 (!N1C->isNullValue() && Cond == ISD::SETNE); 3613 3614 if (!Inverse) 3615 return TopSetCC; 3616 3617 ISD::CondCode InvCond = ISD::getSetCCInverse( 3618 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 3619 TopSetCC.getOperand(0).getValueType()); 3620 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 3621 TopSetCC.getOperand(1), 3622 InvCond); 3623 } 3624 } 3625 } 3626 3627 // If the LHS is '(and load, const)', the RHS is 0, the test is for 3628 // equality or unsigned, and all 1 bits of the const are in the same 3629 // partial word, see if we can shorten the load. 3630 if (DCI.isBeforeLegalize() && 3631 !ISD::isSignedIntSetCC(Cond) && 3632 N0.getOpcode() == ISD::AND && C1 == 0 && 3633 N0.getNode()->hasOneUse() && 3634 isa<LoadSDNode>(N0.getOperand(0)) && 3635 N0.getOperand(0).getNode()->hasOneUse() && 3636 isa<ConstantSDNode>(N0.getOperand(1))) { 3637 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 3638 APInt bestMask; 3639 unsigned bestWidth = 0, bestOffset = 0; 3640 if (Lod->isSimple() && Lod->isUnindexed()) { 3641 unsigned origWidth = N0.getValueSizeInBits(); 3642 unsigned maskWidth = origWidth; 3643 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 3644 // 8 bits, but have to be careful... 3645 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 3646 origWidth = Lod->getMemoryVT().getSizeInBits(); 3647 const APInt &Mask = N0.getConstantOperandAPInt(1); 3648 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 3649 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 3650 for (unsigned offset=0; offset<origWidth/width; offset++) { 3651 if (Mask.isSubsetOf(newMask)) { 3652 if (Layout.isLittleEndian()) 3653 bestOffset = (uint64_t)offset * (width/8); 3654 else 3655 bestOffset = (origWidth/width - offset - 1) * (width/8); 3656 bestMask = Mask.lshr(offset * (width/8) * 8); 3657 bestWidth = width; 3658 break; 3659 } 3660 newMask <<= width; 3661 } 3662 } 3663 } 3664 if (bestWidth) { 3665 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 3666 if (newVT.isRound() && 3667 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 3668 SDValue Ptr = Lod->getBasePtr(); 3669 if (bestOffset != 0) 3670 Ptr = 3671 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 3672 SDValue NewLoad = 3673 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 3674 Lod->getPointerInfo().getWithOffset(bestOffset), 3675 Lod->getOriginalAlign()); 3676 return DAG.getSetCC(dl, VT, 3677 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 3678 DAG.getConstant(bestMask.trunc(bestWidth), 3679 dl, newVT)), 3680 DAG.getConstant(0LL, dl, newVT), Cond); 3681 } 3682 } 3683 } 3684 3685 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 3686 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 3687 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 3688 3689 // If the comparison constant has bits in the upper part, the 3690 // zero-extended value could never match. 3691 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 3692 C1.getBitWidth() - InSize))) { 3693 switch (Cond) { 3694 case ISD::SETUGT: 3695 case ISD::SETUGE: 3696 case ISD::SETEQ: 3697 return DAG.getConstant(0, dl, VT); 3698 case ISD::SETULT: 3699 case ISD::SETULE: 3700 case ISD::SETNE: 3701 return DAG.getConstant(1, dl, VT); 3702 case ISD::SETGT: 3703 case ISD::SETGE: 3704 // True if the sign bit of C1 is set. 3705 return DAG.getConstant(C1.isNegative(), dl, VT); 3706 case ISD::SETLT: 3707 case ISD::SETLE: 3708 // True if the sign bit of C1 isn't set. 3709 return DAG.getConstant(C1.isNonNegative(), dl, VT); 3710 default: 3711 break; 3712 } 3713 } 3714 3715 // Otherwise, we can perform the comparison with the low bits. 3716 switch (Cond) { 3717 case ISD::SETEQ: 3718 case ISD::SETNE: 3719 case ISD::SETUGT: 3720 case ISD::SETUGE: 3721 case ISD::SETULT: 3722 case ISD::SETULE: { 3723 EVT newVT = N0.getOperand(0).getValueType(); 3724 if (DCI.isBeforeLegalizeOps() || 3725 (isOperationLegal(ISD::SETCC, newVT) && 3726 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 3727 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 3728 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 3729 3730 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 3731 NewConst, Cond); 3732 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 3733 } 3734 break; 3735 } 3736 default: 3737 break; // todo, be more careful with signed comparisons 3738 } 3739 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 3740 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3741 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 3742 OpVT)) { 3743 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 3744 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 3745 EVT ExtDstTy = N0.getValueType(); 3746 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 3747 3748 // If the constant doesn't fit into the number of bits for the source of 3749 // the sign extension, it is impossible for both sides to be equal. 3750 if (C1.getMinSignedBits() > ExtSrcTyBits) 3751 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 3752 3753 assert(ExtDstTy == N0.getOperand(0).getValueType() && 3754 ExtDstTy != ExtSrcTy && "Unexpected types!"); 3755 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 3756 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 3757 DAG.getConstant(Imm, dl, ExtDstTy)); 3758 if (!DCI.isCalledByLegalizer()) 3759 DCI.AddToWorklist(ZextOp.getNode()); 3760 // Otherwise, make this a use of a zext. 3761 return DAG.getSetCC(dl, VT, ZextOp, 3762 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 3763 } else if ((N1C->isNullValue() || N1C->isOne()) && 3764 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3765 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 3766 if (N0.getOpcode() == ISD::SETCC && 3767 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 3768 (N0.getValueType() == MVT::i1 || 3769 getBooleanContents(N0.getOperand(0).getValueType()) == 3770 ZeroOrOneBooleanContent)) { 3771 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 3772 if (TrueWhenTrue) 3773 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 3774 // Invert the condition. 3775 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 3776 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 3777 if (DCI.isBeforeLegalizeOps() || 3778 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 3779 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 3780 } 3781 3782 if ((N0.getOpcode() == ISD::XOR || 3783 (N0.getOpcode() == ISD::AND && 3784 N0.getOperand(0).getOpcode() == ISD::XOR && 3785 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 3786 isOneConstant(N0.getOperand(1))) { 3787 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 3788 // can only do this if the top bits are known zero. 3789 unsigned BitWidth = N0.getValueSizeInBits(); 3790 if (DAG.MaskedValueIsZero(N0, 3791 APInt::getHighBitsSet(BitWidth, 3792 BitWidth-1))) { 3793 // Okay, get the un-inverted input value. 3794 SDValue Val; 3795 if (N0.getOpcode() == ISD::XOR) { 3796 Val = N0.getOperand(0); 3797 } else { 3798 assert(N0.getOpcode() == ISD::AND && 3799 N0.getOperand(0).getOpcode() == ISD::XOR); 3800 // ((X^1)&1)^1 -> X & 1 3801 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 3802 N0.getOperand(0).getOperand(0), 3803 N0.getOperand(1)); 3804 } 3805 3806 return DAG.getSetCC(dl, VT, Val, N1, 3807 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3808 } 3809 } else if (N1C->isOne()) { 3810 SDValue Op0 = N0; 3811 if (Op0.getOpcode() == ISD::TRUNCATE) 3812 Op0 = Op0.getOperand(0); 3813 3814 if ((Op0.getOpcode() == ISD::XOR) && 3815 Op0.getOperand(0).getOpcode() == ISD::SETCC && 3816 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 3817 SDValue XorLHS = Op0.getOperand(0); 3818 SDValue XorRHS = Op0.getOperand(1); 3819 // Ensure that the input setccs return an i1 type or 0/1 value. 3820 if (Op0.getValueType() == MVT::i1 || 3821 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 3822 ZeroOrOneBooleanContent && 3823 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 3824 ZeroOrOneBooleanContent)) { 3825 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 3826 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 3827 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 3828 } 3829 } 3830 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 3831 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 3832 if (Op0.getValueType().bitsGT(VT)) 3833 Op0 = DAG.getNode(ISD::AND, dl, VT, 3834 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 3835 DAG.getConstant(1, dl, VT)); 3836 else if (Op0.getValueType().bitsLT(VT)) 3837 Op0 = DAG.getNode(ISD::AND, dl, VT, 3838 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 3839 DAG.getConstant(1, dl, VT)); 3840 3841 return DAG.getSetCC(dl, VT, Op0, 3842 DAG.getConstant(0, dl, Op0.getValueType()), 3843 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3844 } 3845 if (Op0.getOpcode() == ISD::AssertZext && 3846 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 3847 return DAG.getSetCC(dl, VT, Op0, 3848 DAG.getConstant(0, dl, Op0.getValueType()), 3849 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3850 } 3851 } 3852 3853 // Given: 3854 // icmp eq/ne (urem %x, %y), 0 3855 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 3856 // icmp eq/ne %x, 0 3857 if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() && 3858 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3859 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 3860 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 3861 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 3862 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 3863 } 3864 3865 if (SDValue V = 3866 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 3867 return V; 3868 } 3869 3870 // These simplifications apply to splat vectors as well. 3871 // TODO: Handle more splat vector cases. 3872 if (auto *N1C = isConstOrConstSplat(N1)) { 3873 const APInt &C1 = N1C->getAPIntValue(); 3874 3875 APInt MinVal, MaxVal; 3876 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 3877 if (ISD::isSignedIntSetCC(Cond)) { 3878 MinVal = APInt::getSignedMinValue(OperandBitSize); 3879 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 3880 } else { 3881 MinVal = APInt::getMinValue(OperandBitSize); 3882 MaxVal = APInt::getMaxValue(OperandBitSize); 3883 } 3884 3885 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 3886 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 3887 // X >= MIN --> true 3888 if (C1 == MinVal) 3889 return DAG.getBoolConstant(true, dl, VT, OpVT); 3890 3891 if (!VT.isVector()) { // TODO: Support this for vectors. 3892 // X >= C0 --> X > (C0 - 1) 3893 APInt C = C1 - 1; 3894 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 3895 if ((DCI.isBeforeLegalizeOps() || 3896 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3897 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3898 isLegalICmpImmediate(C.getSExtValue())))) { 3899 return DAG.getSetCC(dl, VT, N0, 3900 DAG.getConstant(C, dl, N1.getValueType()), 3901 NewCC); 3902 } 3903 } 3904 } 3905 3906 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 3907 // X <= MAX --> true 3908 if (C1 == MaxVal) 3909 return DAG.getBoolConstant(true, dl, VT, OpVT); 3910 3911 // X <= C0 --> X < (C0 + 1) 3912 if (!VT.isVector()) { // TODO: Support this for vectors. 3913 APInt C = C1 + 1; 3914 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 3915 if ((DCI.isBeforeLegalizeOps() || 3916 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3917 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3918 isLegalICmpImmediate(C.getSExtValue())))) { 3919 return DAG.getSetCC(dl, VT, N0, 3920 DAG.getConstant(C, dl, N1.getValueType()), 3921 NewCC); 3922 } 3923 } 3924 } 3925 3926 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 3927 if (C1 == MinVal) 3928 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 3929 3930 // TODO: Support this for vectors after legalize ops. 3931 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3932 // Canonicalize setlt X, Max --> setne X, Max 3933 if (C1 == MaxVal) 3934 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3935 3936 // If we have setult X, 1, turn it into seteq X, 0 3937 if (C1 == MinVal+1) 3938 return DAG.getSetCC(dl, VT, N0, 3939 DAG.getConstant(MinVal, dl, N0.getValueType()), 3940 ISD::SETEQ); 3941 } 3942 } 3943 3944 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 3945 if (C1 == MaxVal) 3946 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 3947 3948 // TODO: Support this for vectors after legalize ops. 3949 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3950 // Canonicalize setgt X, Min --> setne X, Min 3951 if (C1 == MinVal) 3952 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3953 3954 // If we have setugt X, Max-1, turn it into seteq X, Max 3955 if (C1 == MaxVal-1) 3956 return DAG.getSetCC(dl, VT, N0, 3957 DAG.getConstant(MaxVal, dl, N0.getValueType()), 3958 ISD::SETEQ); 3959 } 3960 } 3961 3962 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 3963 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3964 if (C1.isNullValue()) 3965 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 3966 VT, N0, N1, Cond, DCI, dl)) 3967 return CC; 3968 3969 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 3970 // For example, when high 32-bits of i64 X are known clear: 3971 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 3972 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 3973 bool CmpZero = N1C->getAPIntValue().isNullValue(); 3974 bool CmpNegOne = N1C->getAPIntValue().isAllOnesValue(); 3975 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 3976 // Match or(lo,shl(hi,bw/2)) pattern. 3977 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 3978 unsigned EltBits = V.getScalarValueSizeInBits(); 3979 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 3980 return false; 3981 SDValue LHS = V.getOperand(0); 3982 SDValue RHS = V.getOperand(1); 3983 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 3984 // Unshifted element must have zero upperbits. 3985 if (RHS.getOpcode() == ISD::SHL && 3986 isa<ConstantSDNode>(RHS.getOperand(1)) && 3987 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3988 DAG.MaskedValueIsZero(LHS, HiBits)) { 3989 Lo = LHS; 3990 Hi = RHS.getOperand(0); 3991 return true; 3992 } 3993 if (LHS.getOpcode() == ISD::SHL && 3994 isa<ConstantSDNode>(LHS.getOperand(1)) && 3995 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3996 DAG.MaskedValueIsZero(RHS, HiBits)) { 3997 Lo = RHS; 3998 Hi = LHS.getOperand(0); 3999 return true; 4000 } 4001 return false; 4002 }; 4003 4004 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4005 unsigned EltBits = N0.getScalarValueSizeInBits(); 4006 unsigned HalfBits = EltBits / 2; 4007 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4008 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4009 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4010 SDValue NewN0 = 4011 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4012 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4013 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4014 }; 4015 4016 SDValue Lo, Hi; 4017 if (IsConcat(N0, Lo, Hi)) 4018 return MergeConcat(Lo, Hi); 4019 4020 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4021 SDValue Lo0, Lo1, Hi0, Hi1; 4022 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4023 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4024 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4025 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4026 } 4027 } 4028 } 4029 } 4030 4031 // If we have "setcc X, C0", check to see if we can shrink the immediate 4032 // by changing cc. 4033 // TODO: Support this for vectors after legalize ops. 4034 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4035 // SETUGT X, SINTMAX -> SETLT X, 0 4036 // SETUGE X, SINTMIN -> SETLT X, 0 4037 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4038 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4039 return DAG.getSetCC(dl, VT, N0, 4040 DAG.getConstant(0, dl, N1.getValueType()), 4041 ISD::SETLT); 4042 4043 // SETULT X, SINTMIN -> SETGT X, -1 4044 // SETULE X, SINTMAX -> SETGT X, -1 4045 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4046 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4047 return DAG.getSetCC(dl, VT, N0, 4048 DAG.getAllOnesConstant(dl, N1.getValueType()), 4049 ISD::SETGT); 4050 } 4051 } 4052 4053 // Back to non-vector simplifications. 4054 // TODO: Can we do these for vector splats? 4055 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4056 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4057 const APInt &C1 = N1C->getAPIntValue(); 4058 EVT ShValTy = N0.getValueType(); 4059 4060 // Fold bit comparisons when we can. This will result in an 4061 // incorrect value when boolean false is negative one, unless 4062 // the bitsize is 1 in which case the false value is the same 4063 // in practice regardless of the representation. 4064 if ((VT.getSizeInBits() == 1 || 4065 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4066 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4067 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4068 N0.getOpcode() == ISD::AND) { 4069 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4070 EVT ShiftTy = 4071 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4072 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4073 // Perform the xform if the AND RHS is a single bit. 4074 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4075 if (AndRHS->getAPIntValue().isPowerOf2() && 4076 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4077 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4078 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4079 DAG.getConstant(ShCt, dl, ShiftTy))); 4080 } 4081 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4082 // (X & 8) == 8 --> (X & 8) >> 3 4083 // Perform the xform if C1 is a single bit. 4084 unsigned ShCt = C1.logBase2(); 4085 if (C1.isPowerOf2() && 4086 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4087 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4088 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4089 DAG.getConstant(ShCt, dl, ShiftTy))); 4090 } 4091 } 4092 } 4093 } 4094 4095 if (C1.getMinSignedBits() <= 64 && 4096 !isLegalICmpImmediate(C1.getSExtValue())) { 4097 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4098 // (X & -256) == 256 -> (X >> 8) == 1 4099 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4100 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4101 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4102 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4103 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 4104 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4105 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4106 SDValue Shift = 4107 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4108 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4109 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4110 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4111 } 4112 } 4113 } 4114 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4115 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4116 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4117 // X < 0x100000000 -> (X >> 32) < 1 4118 // X >= 0x100000000 -> (X >> 32) >= 1 4119 // X <= 0x0ffffffff -> (X >> 32) < 1 4120 // X > 0x0ffffffff -> (X >> 32) >= 1 4121 unsigned ShiftBits; 4122 APInt NewC = C1; 4123 ISD::CondCode NewCond = Cond; 4124 if (AdjOne) { 4125 ShiftBits = C1.countTrailingOnes(); 4126 NewC = NewC + 1; 4127 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4128 } else { 4129 ShiftBits = C1.countTrailingZeros(); 4130 } 4131 NewC.lshrInPlace(ShiftBits); 4132 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4133 isLegalICmpImmediate(NewC.getSExtValue()) && 4134 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4135 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4136 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4137 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4138 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4139 } 4140 } 4141 } 4142 } 4143 4144 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4145 auto *CFP = cast<ConstantFPSDNode>(N1); 4146 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4147 4148 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4149 // constant if knowing that the operand is non-nan is enough. We prefer to 4150 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4151 // materialize 0.0. 4152 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4153 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4154 4155 // setcc (fneg x), C -> setcc swap(pred) x, -C 4156 if (N0.getOpcode() == ISD::FNEG) { 4157 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4158 if (DCI.isBeforeLegalizeOps() || 4159 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4160 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4161 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4162 } 4163 } 4164 4165 // If the condition is not legal, see if we can find an equivalent one 4166 // which is legal. 4167 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4168 // If the comparison was an awkward floating-point == or != and one of 4169 // the comparison operands is infinity or negative infinity, convert the 4170 // condition to a less-awkward <= or >=. 4171 if (CFP->getValueAPF().isInfinity()) { 4172 bool IsNegInf = CFP->getValueAPF().isNegative(); 4173 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4174 switch (Cond) { 4175 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4176 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4177 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4178 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4179 default: break; 4180 } 4181 if (NewCond != ISD::SETCC_INVALID && 4182 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4183 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4184 } 4185 } 4186 } 4187 4188 if (N0 == N1) { 4189 // The sext(setcc()) => setcc() optimization relies on the appropriate 4190 // constant being emitted. 4191 assert(!N0.getValueType().isInteger() && 4192 "Integer types should be handled by FoldSetCC"); 4193 4194 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4195 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4196 if (UOF == 2) // FP operators that are undefined on NaNs. 4197 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4198 if (UOF == unsigned(EqTrue)) 4199 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4200 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4201 // if it is not already. 4202 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4203 if (NewCond != Cond && 4204 (DCI.isBeforeLegalizeOps() || 4205 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4206 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4207 } 4208 4209 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4210 N0.getValueType().isInteger()) { 4211 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4212 N0.getOpcode() == ISD::XOR) { 4213 // Simplify (X+Y) == (X+Z) --> Y == Z 4214 if (N0.getOpcode() == N1.getOpcode()) { 4215 if (N0.getOperand(0) == N1.getOperand(0)) 4216 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4217 if (N0.getOperand(1) == N1.getOperand(1)) 4218 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4219 if (isCommutativeBinOp(N0.getOpcode())) { 4220 // If X op Y == Y op X, try other combinations. 4221 if (N0.getOperand(0) == N1.getOperand(1)) 4222 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4223 Cond); 4224 if (N0.getOperand(1) == N1.getOperand(0)) 4225 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4226 Cond); 4227 } 4228 } 4229 4230 // If RHS is a legal immediate value for a compare instruction, we need 4231 // to be careful about increasing register pressure needlessly. 4232 bool LegalRHSImm = false; 4233 4234 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4235 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4236 // Turn (X+C1) == C2 --> X == C2-C1 4237 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 4238 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4239 DAG.getConstant(RHSC->getAPIntValue()- 4240 LHSR->getAPIntValue(), 4241 dl, N0.getValueType()), Cond); 4242 } 4243 4244 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 4245 if (N0.getOpcode() == ISD::XOR) 4246 // If we know that all of the inverted bits are zero, don't bother 4247 // performing the inversion. 4248 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 4249 return 4250 DAG.getSetCC(dl, VT, N0.getOperand(0), 4251 DAG.getConstant(LHSR->getAPIntValue() ^ 4252 RHSC->getAPIntValue(), 4253 dl, N0.getValueType()), 4254 Cond); 4255 } 4256 4257 // Turn (C1-X) == C2 --> X == C1-C2 4258 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 4259 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 4260 return 4261 DAG.getSetCC(dl, VT, N0.getOperand(1), 4262 DAG.getConstant(SUBC->getAPIntValue() - 4263 RHSC->getAPIntValue(), 4264 dl, N0.getValueType()), 4265 Cond); 4266 } 4267 } 4268 4269 // Could RHSC fold directly into a compare? 4270 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4271 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4272 } 4273 4274 // (X+Y) == X --> Y == 0 and similar folds. 4275 // Don't do this if X is an immediate that can fold into a cmp 4276 // instruction and X+Y has other uses. It could be an induction variable 4277 // chain, and the transform would increase register pressure. 4278 if (!LegalRHSImm || N0.hasOneUse()) 4279 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4280 return V; 4281 } 4282 4283 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4284 N1.getOpcode() == ISD::XOR) 4285 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4286 return V; 4287 4288 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4289 return V; 4290 } 4291 4292 // Fold remainder of division by a constant. 4293 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4294 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4295 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4296 4297 // When division is cheap or optimizing for minimum size, 4298 // fall through to DIVREM creation by skipping this fold. 4299 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) { 4300 if (N0.getOpcode() == ISD::UREM) { 4301 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4302 return Folded; 4303 } else if (N0.getOpcode() == ISD::SREM) { 4304 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4305 return Folded; 4306 } 4307 } 4308 } 4309 4310 // Fold away ALL boolean setcc's. 4311 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4312 SDValue Temp; 4313 switch (Cond) { 4314 default: llvm_unreachable("Unknown integer setcc!"); 4315 case ISD::SETEQ: // X == Y -> ~(X^Y) 4316 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4317 N0 = DAG.getNOT(dl, Temp, OpVT); 4318 if (!DCI.isCalledByLegalizer()) 4319 DCI.AddToWorklist(Temp.getNode()); 4320 break; 4321 case ISD::SETNE: // X != Y --> (X^Y) 4322 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4323 break; 4324 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4325 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4326 Temp = DAG.getNOT(dl, N0, OpVT); 4327 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4328 if (!DCI.isCalledByLegalizer()) 4329 DCI.AddToWorklist(Temp.getNode()); 4330 break; 4331 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4332 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4333 Temp = DAG.getNOT(dl, N1, OpVT); 4334 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4335 if (!DCI.isCalledByLegalizer()) 4336 DCI.AddToWorklist(Temp.getNode()); 4337 break; 4338 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4339 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4340 Temp = DAG.getNOT(dl, N0, OpVT); 4341 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4342 if (!DCI.isCalledByLegalizer()) 4343 DCI.AddToWorklist(Temp.getNode()); 4344 break; 4345 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4346 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4347 Temp = DAG.getNOT(dl, N1, OpVT); 4348 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4349 break; 4350 } 4351 if (VT.getScalarType() != MVT::i1) { 4352 if (!DCI.isCalledByLegalizer()) 4353 DCI.AddToWorklist(N0.getNode()); 4354 // FIXME: If running after legalize, we probably can't do this. 4355 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4356 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4357 } 4358 return N0; 4359 } 4360 4361 // Could not fold it. 4362 return SDValue(); 4363 } 4364 4365 /// Returns true (and the GlobalValue and the offset) if the node is a 4366 /// GlobalAddress + offset. 4367 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4368 int64_t &Offset) const { 4369 4370 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4371 4372 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4373 GA = GASD->getGlobal(); 4374 Offset += GASD->getOffset(); 4375 return true; 4376 } 4377 4378 if (N->getOpcode() == ISD::ADD) { 4379 SDValue N1 = N->getOperand(0); 4380 SDValue N2 = N->getOperand(1); 4381 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4382 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4383 Offset += V->getSExtValue(); 4384 return true; 4385 } 4386 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4387 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4388 Offset += V->getSExtValue(); 4389 return true; 4390 } 4391 } 4392 } 4393 4394 return false; 4395 } 4396 4397 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4398 DAGCombinerInfo &DCI) const { 4399 // Default implementation: no optimization. 4400 return SDValue(); 4401 } 4402 4403 //===----------------------------------------------------------------------===// 4404 // Inline Assembler Implementation Methods 4405 //===----------------------------------------------------------------------===// 4406 4407 TargetLowering::ConstraintType 4408 TargetLowering::getConstraintType(StringRef Constraint) const { 4409 unsigned S = Constraint.size(); 4410 4411 if (S == 1) { 4412 switch (Constraint[0]) { 4413 default: break; 4414 case 'r': 4415 return C_RegisterClass; 4416 case 'm': // memory 4417 case 'o': // offsetable 4418 case 'V': // not offsetable 4419 return C_Memory; 4420 case 'n': // Simple Integer 4421 case 'E': // Floating Point Constant 4422 case 'F': // Floating Point Constant 4423 return C_Immediate; 4424 case 'i': // Simple Integer or Relocatable Constant 4425 case 's': // Relocatable Constant 4426 case 'p': // Address. 4427 case 'X': // Allow ANY value. 4428 case 'I': // Target registers. 4429 case 'J': 4430 case 'K': 4431 case 'L': 4432 case 'M': 4433 case 'N': 4434 case 'O': 4435 case 'P': 4436 case '<': 4437 case '>': 4438 return C_Other; 4439 } 4440 } 4441 4442 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4443 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4444 return C_Memory; 4445 return C_Register; 4446 } 4447 return C_Unknown; 4448 } 4449 4450 /// Try to replace an X constraint, which matches anything, with another that 4451 /// has more specific requirements based on the type of the corresponding 4452 /// operand. 4453 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4454 if (ConstraintVT.isInteger()) 4455 return "r"; 4456 if (ConstraintVT.isFloatingPoint()) 4457 return "f"; // works for many targets 4458 return nullptr; 4459 } 4460 4461 SDValue TargetLowering::LowerAsmOutputForConstraint( 4462 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4463 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4464 return SDValue(); 4465 } 4466 4467 /// Lower the specified operand into the Ops vector. 4468 /// If it is invalid, don't add anything to Ops. 4469 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4470 std::string &Constraint, 4471 std::vector<SDValue> &Ops, 4472 SelectionDAG &DAG) const { 4473 4474 if (Constraint.length() > 1) return; 4475 4476 char ConstraintLetter = Constraint[0]; 4477 switch (ConstraintLetter) { 4478 default: break; 4479 case 'X': // Allows any operand; labels (basic block) use this. 4480 if (Op.getOpcode() == ISD::BasicBlock || 4481 Op.getOpcode() == ISD::TargetBlockAddress) { 4482 Ops.push_back(Op); 4483 return; 4484 } 4485 LLVM_FALLTHROUGH; 4486 case 'i': // Simple Integer or Relocatable Constant 4487 case 'n': // Simple Integer 4488 case 's': { // Relocatable Constant 4489 4490 GlobalAddressSDNode *GA; 4491 ConstantSDNode *C; 4492 BlockAddressSDNode *BA; 4493 uint64_t Offset = 0; 4494 4495 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 4496 // etc., since getelementpointer is variadic. We can't use 4497 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 4498 // while in this case the GA may be furthest from the root node which is 4499 // likely an ISD::ADD. 4500 while (1) { 4501 if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') { 4502 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 4503 GA->getValueType(0), 4504 Offset + GA->getOffset())); 4505 return; 4506 } 4507 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 4508 // gcc prints these as sign extended. Sign extend value to 64 bits 4509 // now; without this it would get ZExt'd later in 4510 // ScheduleDAGSDNodes::EmitNode, which is very generic. 4511 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 4512 BooleanContent BCont = getBooleanContents(MVT::i64); 4513 ISD::NodeType ExtOpc = 4514 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 4515 int64_t ExtVal = 4516 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 4517 Ops.push_back( 4518 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 4519 return; 4520 } 4521 if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && ConstraintLetter != 'n') { 4522 Ops.push_back(DAG.getTargetBlockAddress( 4523 BA->getBlockAddress(), BA->getValueType(0), 4524 Offset + BA->getOffset(), BA->getTargetFlags())); 4525 return; 4526 } 4527 const unsigned OpCode = Op.getOpcode(); 4528 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 4529 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 4530 Op = Op.getOperand(1); 4531 // Subtraction is not commutative. 4532 else if (OpCode == ISD::ADD && 4533 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 4534 Op = Op.getOperand(0); 4535 else 4536 return; 4537 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 4538 continue; 4539 } 4540 return; 4541 } 4542 break; 4543 } 4544 } 4545 } 4546 4547 std::pair<unsigned, const TargetRegisterClass *> 4548 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4549 StringRef Constraint, 4550 MVT VT) const { 4551 if (Constraint.empty() || Constraint[0] != '{') 4552 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4553 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4554 4555 // Remove the braces from around the name. 4556 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4557 4558 std::pair<unsigned, const TargetRegisterClass *> R = 4559 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4560 4561 // Figure out which register class contains this reg. 4562 for (const TargetRegisterClass *RC : RI->regclasses()) { 4563 // If none of the value types for this register class are valid, we 4564 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4565 if (!isLegalRC(*RI, *RC)) 4566 continue; 4567 4568 for (const MCPhysReg &PR : *RC) { 4569 if (RegName.equals_lower(RI->getRegAsmName(PR))) { 4570 std::pair<unsigned, const TargetRegisterClass *> S = 4571 std::make_pair(PR, RC); 4572 4573 // If this register class has the requested value type, return it, 4574 // otherwise keep searching and return the first class found 4575 // if no other is found which explicitly has the requested type. 4576 if (RI->isTypeLegalForClass(*RC, VT)) 4577 return S; 4578 if (!R.second) 4579 R = S; 4580 } 4581 } 4582 } 4583 4584 return R; 4585 } 4586 4587 //===----------------------------------------------------------------------===// 4588 // Constraint Selection. 4589 4590 /// Return true of this is an input operand that is a matching constraint like 4591 /// "4". 4592 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4593 assert(!ConstraintCode.empty() && "No known constraint!"); 4594 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4595 } 4596 4597 /// If this is an input matching constraint, this method returns the output 4598 /// operand it matches. 4599 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 4600 assert(!ConstraintCode.empty() && "No known constraint!"); 4601 return atoi(ConstraintCode.c_str()); 4602 } 4603 4604 /// Split up the constraint string from the inline assembly value into the 4605 /// specific constraints and their prefixes, and also tie in the associated 4606 /// operand values. 4607 /// If this returns an empty vector, and if the constraint string itself 4608 /// isn't empty, there was an error parsing. 4609 TargetLowering::AsmOperandInfoVector 4610 TargetLowering::ParseConstraints(const DataLayout &DL, 4611 const TargetRegisterInfo *TRI, 4612 const CallBase &Call) const { 4613 /// Information about all of the constraints. 4614 AsmOperandInfoVector ConstraintOperands; 4615 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 4616 unsigned maCount = 0; // Largest number of multiple alternative constraints. 4617 4618 // Do a prepass over the constraints, canonicalizing them, and building up the 4619 // ConstraintOperands list. 4620 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 4621 unsigned ResNo = 0; // ResNo - The result number of the next output. 4622 4623 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4624 ConstraintOperands.emplace_back(std::move(CI)); 4625 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 4626 4627 // Update multiple alternative constraint count. 4628 if (OpInfo.multipleAlternatives.size() > maCount) 4629 maCount = OpInfo.multipleAlternatives.size(); 4630 4631 OpInfo.ConstraintVT = MVT::Other; 4632 4633 // Compute the value type for each operand. 4634 switch (OpInfo.Type) { 4635 case InlineAsm::isOutput: 4636 // Indirect outputs just consume an argument. 4637 if (OpInfo.isIndirect) { 4638 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4639 break; 4640 } 4641 4642 // The return value of the call is this value. As such, there is no 4643 // corresponding argument. 4644 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 4645 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 4646 OpInfo.ConstraintVT = 4647 getSimpleValueType(DL, STy->getElementType(ResNo)); 4648 } else { 4649 assert(ResNo == 0 && "Asm only has one result!"); 4650 OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType()); 4651 } 4652 ++ResNo; 4653 break; 4654 case InlineAsm::isInput: 4655 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4656 break; 4657 case InlineAsm::isClobber: 4658 // Nothing to do. 4659 break; 4660 } 4661 4662 if (OpInfo.CallOperandVal) { 4663 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 4664 if (OpInfo.isIndirect) { 4665 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 4666 if (!PtrTy) 4667 report_fatal_error("Indirect operand for inline asm not a pointer!"); 4668 OpTy = PtrTy->getElementType(); 4669 } 4670 4671 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 4672 if (StructType *STy = dyn_cast<StructType>(OpTy)) 4673 if (STy->getNumElements() == 1) 4674 OpTy = STy->getElementType(0); 4675 4676 // If OpTy is not a single value, it may be a struct/union that we 4677 // can tile with integers. 4678 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4679 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 4680 switch (BitSize) { 4681 default: break; 4682 case 1: 4683 case 8: 4684 case 16: 4685 case 32: 4686 case 64: 4687 case 128: 4688 OpInfo.ConstraintVT = 4689 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 4690 break; 4691 } 4692 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 4693 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 4694 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 4695 } else { 4696 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 4697 } 4698 } 4699 } 4700 4701 // If we have multiple alternative constraints, select the best alternative. 4702 if (!ConstraintOperands.empty()) { 4703 if (maCount) { 4704 unsigned bestMAIndex = 0; 4705 int bestWeight = -1; 4706 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 4707 int weight = -1; 4708 unsigned maIndex; 4709 // Compute the sums of the weights for each alternative, keeping track 4710 // of the best (highest weight) one so far. 4711 for (maIndex = 0; maIndex < maCount; ++maIndex) { 4712 int weightSum = 0; 4713 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4714 cIndex != eIndex; ++cIndex) { 4715 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4716 if (OpInfo.Type == InlineAsm::isClobber) 4717 continue; 4718 4719 // If this is an output operand with a matching input operand, 4720 // look up the matching input. If their types mismatch, e.g. one 4721 // is an integer, the other is floating point, or their sizes are 4722 // different, flag it as an maCantMatch. 4723 if (OpInfo.hasMatchingInput()) { 4724 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4725 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4726 if ((OpInfo.ConstraintVT.isInteger() != 4727 Input.ConstraintVT.isInteger()) || 4728 (OpInfo.ConstraintVT.getSizeInBits() != 4729 Input.ConstraintVT.getSizeInBits())) { 4730 weightSum = -1; // Can't match. 4731 break; 4732 } 4733 } 4734 } 4735 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 4736 if (weight == -1) { 4737 weightSum = -1; 4738 break; 4739 } 4740 weightSum += weight; 4741 } 4742 // Update best. 4743 if (weightSum > bestWeight) { 4744 bestWeight = weightSum; 4745 bestMAIndex = maIndex; 4746 } 4747 } 4748 4749 // Now select chosen alternative in each constraint. 4750 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4751 cIndex != eIndex; ++cIndex) { 4752 AsmOperandInfo &cInfo = ConstraintOperands[cIndex]; 4753 if (cInfo.Type == InlineAsm::isClobber) 4754 continue; 4755 cInfo.selectAlternative(bestMAIndex); 4756 } 4757 } 4758 } 4759 4760 // Check and hook up tied operands, choose constraint code to use. 4761 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4762 cIndex != eIndex; ++cIndex) { 4763 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4764 4765 // If this is an output operand with a matching input operand, look up the 4766 // matching input. If their types mismatch, e.g. one is an integer, the 4767 // other is floating point, or their sizes are different, flag it as an 4768 // error. 4769 if (OpInfo.hasMatchingInput()) { 4770 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4771 4772 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4773 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 4774 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 4775 OpInfo.ConstraintVT); 4776 std::pair<unsigned, const TargetRegisterClass *> InputRC = 4777 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 4778 Input.ConstraintVT); 4779 if ((OpInfo.ConstraintVT.isInteger() != 4780 Input.ConstraintVT.isInteger()) || 4781 (MatchRC.second != InputRC.second)) { 4782 report_fatal_error("Unsupported asm: input constraint" 4783 " with a matching output constraint of" 4784 " incompatible type!"); 4785 } 4786 } 4787 } 4788 } 4789 4790 return ConstraintOperands; 4791 } 4792 4793 /// Return an integer indicating how general CT is. 4794 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 4795 switch (CT) { 4796 case TargetLowering::C_Immediate: 4797 case TargetLowering::C_Other: 4798 case TargetLowering::C_Unknown: 4799 return 0; 4800 case TargetLowering::C_Register: 4801 return 1; 4802 case TargetLowering::C_RegisterClass: 4803 return 2; 4804 case TargetLowering::C_Memory: 4805 return 3; 4806 } 4807 llvm_unreachable("Invalid constraint type"); 4808 } 4809 4810 /// Examine constraint type and operand type and determine a weight value. 4811 /// This object must already have been set up with the operand type 4812 /// and the current alternative constraint selected. 4813 TargetLowering::ConstraintWeight 4814 TargetLowering::getMultipleConstraintMatchWeight( 4815 AsmOperandInfo &info, int maIndex) const { 4816 InlineAsm::ConstraintCodeVector *rCodes; 4817 if (maIndex >= (int)info.multipleAlternatives.size()) 4818 rCodes = &info.Codes; 4819 else 4820 rCodes = &info.multipleAlternatives[maIndex].Codes; 4821 ConstraintWeight BestWeight = CW_Invalid; 4822 4823 // Loop over the options, keeping track of the most general one. 4824 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 4825 ConstraintWeight weight = 4826 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 4827 if (weight > BestWeight) 4828 BestWeight = weight; 4829 } 4830 4831 return BestWeight; 4832 } 4833 4834 /// Examine constraint type and operand type and determine a weight value. 4835 /// This object must already have been set up with the operand type 4836 /// and the current alternative constraint selected. 4837 TargetLowering::ConstraintWeight 4838 TargetLowering::getSingleConstraintMatchWeight( 4839 AsmOperandInfo &info, const char *constraint) const { 4840 ConstraintWeight weight = CW_Invalid; 4841 Value *CallOperandVal = info.CallOperandVal; 4842 // If we don't have a value, we can't do a match, 4843 // but allow it at the lowest weight. 4844 if (!CallOperandVal) 4845 return CW_Default; 4846 // Look at the constraint type. 4847 switch (*constraint) { 4848 case 'i': // immediate integer. 4849 case 'n': // immediate integer with a known value. 4850 if (isa<ConstantInt>(CallOperandVal)) 4851 weight = CW_Constant; 4852 break; 4853 case 's': // non-explicit intregal immediate. 4854 if (isa<GlobalValue>(CallOperandVal)) 4855 weight = CW_Constant; 4856 break; 4857 case 'E': // immediate float if host format. 4858 case 'F': // immediate float. 4859 if (isa<ConstantFP>(CallOperandVal)) 4860 weight = CW_Constant; 4861 break; 4862 case '<': // memory operand with autodecrement. 4863 case '>': // memory operand with autoincrement. 4864 case 'm': // memory operand. 4865 case 'o': // offsettable memory operand 4866 case 'V': // non-offsettable memory operand 4867 weight = CW_Memory; 4868 break; 4869 case 'r': // general register. 4870 case 'g': // general register, memory operand or immediate integer. 4871 // note: Clang converts "g" to "imr". 4872 if (CallOperandVal->getType()->isIntegerTy()) 4873 weight = CW_Register; 4874 break; 4875 case 'X': // any operand. 4876 default: 4877 weight = CW_Default; 4878 break; 4879 } 4880 return weight; 4881 } 4882 4883 /// If there are multiple different constraints that we could pick for this 4884 /// operand (e.g. "imr") try to pick the 'best' one. 4885 /// This is somewhat tricky: constraints fall into four classes: 4886 /// Other -> immediates and magic values 4887 /// Register -> one specific register 4888 /// RegisterClass -> a group of regs 4889 /// Memory -> memory 4890 /// Ideally, we would pick the most specific constraint possible: if we have 4891 /// something that fits into a register, we would pick it. The problem here 4892 /// is that if we have something that could either be in a register or in 4893 /// memory that use of the register could cause selection of *other* 4894 /// operands to fail: they might only succeed if we pick memory. Because of 4895 /// this the heuristic we use is: 4896 /// 4897 /// 1) If there is an 'other' constraint, and if the operand is valid for 4898 /// that constraint, use it. This makes us take advantage of 'i' 4899 /// constraints when available. 4900 /// 2) Otherwise, pick the most general constraint present. This prefers 4901 /// 'm' over 'r', for example. 4902 /// 4903 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 4904 const TargetLowering &TLI, 4905 SDValue Op, SelectionDAG *DAG) { 4906 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 4907 unsigned BestIdx = 0; 4908 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 4909 int BestGenerality = -1; 4910 4911 // Loop over the options, keeping track of the most general one. 4912 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 4913 TargetLowering::ConstraintType CType = 4914 TLI.getConstraintType(OpInfo.Codes[i]); 4915 4916 // Indirect 'other' or 'immediate' constraints are not allowed. 4917 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 4918 CType == TargetLowering::C_Register || 4919 CType == TargetLowering::C_RegisterClass)) 4920 continue; 4921 4922 // If this is an 'other' or 'immediate' constraint, see if the operand is 4923 // valid for it. For example, on X86 we might have an 'rI' constraint. If 4924 // the operand is an integer in the range [0..31] we want to use I (saving a 4925 // load of a register), otherwise we must use 'r'. 4926 if ((CType == TargetLowering::C_Other || 4927 CType == TargetLowering::C_Immediate) && Op.getNode()) { 4928 assert(OpInfo.Codes[i].size() == 1 && 4929 "Unhandled multi-letter 'other' constraint"); 4930 std::vector<SDValue> ResultOps; 4931 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 4932 ResultOps, *DAG); 4933 if (!ResultOps.empty()) { 4934 BestType = CType; 4935 BestIdx = i; 4936 break; 4937 } 4938 } 4939 4940 // Things with matching constraints can only be registers, per gcc 4941 // documentation. This mainly affects "g" constraints. 4942 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 4943 continue; 4944 4945 // This constraint letter is more general than the previous one, use it. 4946 int Generality = getConstraintGenerality(CType); 4947 if (Generality > BestGenerality) { 4948 BestType = CType; 4949 BestIdx = i; 4950 BestGenerality = Generality; 4951 } 4952 } 4953 4954 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 4955 OpInfo.ConstraintType = BestType; 4956 } 4957 4958 /// Determines the constraint code and constraint type to use for the specific 4959 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 4960 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 4961 SDValue Op, 4962 SelectionDAG *DAG) const { 4963 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 4964 4965 // Single-letter constraints ('r') are very common. 4966 if (OpInfo.Codes.size() == 1) { 4967 OpInfo.ConstraintCode = OpInfo.Codes[0]; 4968 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4969 } else { 4970 ChooseConstraint(OpInfo, *this, Op, DAG); 4971 } 4972 4973 // 'X' matches anything. 4974 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 4975 // Labels and constants are handled elsewhere ('X' is the only thing 4976 // that matches labels). For Functions, the type here is the type of 4977 // the result, which is not what we want to look at; leave them alone. 4978 Value *v = OpInfo.CallOperandVal; 4979 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 4980 OpInfo.CallOperandVal = v; 4981 return; 4982 } 4983 4984 if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress) 4985 return; 4986 4987 // Otherwise, try to resolve it to something we know about by looking at 4988 // the actual operand type. 4989 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 4990 OpInfo.ConstraintCode = Repl; 4991 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4992 } 4993 } 4994 } 4995 4996 /// Given an exact SDIV by a constant, create a multiplication 4997 /// with the multiplicative inverse of the constant. 4998 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 4999 const SDLoc &dl, SelectionDAG &DAG, 5000 SmallVectorImpl<SDNode *> &Created) { 5001 SDValue Op0 = N->getOperand(0); 5002 SDValue Op1 = N->getOperand(1); 5003 EVT VT = N->getValueType(0); 5004 EVT SVT = VT.getScalarType(); 5005 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5006 EVT ShSVT = ShVT.getScalarType(); 5007 5008 bool UseSRA = false; 5009 SmallVector<SDValue, 16> Shifts, Factors; 5010 5011 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5012 if (C->isNullValue()) 5013 return false; 5014 APInt Divisor = C->getAPIntValue(); 5015 unsigned Shift = Divisor.countTrailingZeros(); 5016 if (Shift) { 5017 Divisor.ashrInPlace(Shift); 5018 UseSRA = true; 5019 } 5020 // Calculate the multiplicative inverse, using Newton's method. 5021 APInt t; 5022 APInt Factor = Divisor; 5023 while ((t = Divisor * Factor) != 1) 5024 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5025 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5026 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5027 return true; 5028 }; 5029 5030 // Collect all magic values from the build vector. 5031 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5032 return SDValue(); 5033 5034 SDValue Shift, Factor; 5035 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5036 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5037 Factor = DAG.getBuildVector(VT, dl, Factors); 5038 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5039 assert(Shifts.size() == 1 && Factors.size() == 1 && 5040 "Expected matchUnaryPredicate to return one element for scalable " 5041 "vectors"); 5042 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5043 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5044 } else { 5045 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5046 Shift = Shifts[0]; 5047 Factor = Factors[0]; 5048 } 5049 5050 SDValue Res = Op0; 5051 5052 // Shift the value upfront if it is even, so the LSB is one. 5053 if (UseSRA) { 5054 // TODO: For UDIV use SRL instead of SRA. 5055 SDNodeFlags Flags; 5056 Flags.setExact(true); 5057 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5058 Created.push_back(Res.getNode()); 5059 } 5060 5061 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5062 } 5063 5064 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5065 SelectionDAG &DAG, 5066 SmallVectorImpl<SDNode *> &Created) const { 5067 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5069 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5070 return SDValue(N, 0); // Lower SDIV as SDIV 5071 return SDValue(); 5072 } 5073 5074 /// Given an ISD::SDIV node expressing a divide by constant, 5075 /// return a DAG expression to select that will generate the same value by 5076 /// multiplying by a magic number. 5077 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5078 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5079 bool IsAfterLegalization, 5080 SmallVectorImpl<SDNode *> &Created) const { 5081 SDLoc dl(N); 5082 EVT VT = N->getValueType(0); 5083 EVT SVT = VT.getScalarType(); 5084 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5085 EVT ShSVT = ShVT.getScalarType(); 5086 unsigned EltBits = VT.getScalarSizeInBits(); 5087 EVT MulVT; 5088 5089 // Check to see if we can do this. 5090 // FIXME: We should be more aggressive here. 5091 if (!isTypeLegal(VT)) { 5092 // Limit this to simple scalars for now. 5093 if (VT.isVector() || !VT.isSimple()) 5094 return SDValue(); 5095 5096 // If this type will be promoted to a large enough type with a legal 5097 // multiply operation, we can go ahead and do this transform. 5098 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5099 return SDValue(); 5100 5101 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5102 if (MulVT.getSizeInBits() < (2 * EltBits) || 5103 !isOperationLegal(ISD::MUL, MulVT)) 5104 return SDValue(); 5105 } 5106 5107 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5108 if (N->getFlags().hasExact()) 5109 return BuildExactSDIV(*this, N, dl, DAG, Created); 5110 5111 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5112 5113 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5114 if (C->isNullValue()) 5115 return false; 5116 5117 const APInt &Divisor = C->getAPIntValue(); 5118 APInt::ms magics = Divisor.magic(); 5119 int NumeratorFactor = 0; 5120 int ShiftMask = -1; 5121 5122 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 5123 // If d is +1/-1, we just multiply the numerator by +1/-1. 5124 NumeratorFactor = Divisor.getSExtValue(); 5125 magics.m = 0; 5126 magics.s = 0; 5127 ShiftMask = 0; 5128 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 5129 // If d > 0 and m < 0, add the numerator. 5130 NumeratorFactor = 1; 5131 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 5132 // If d < 0 and m > 0, subtract the numerator. 5133 NumeratorFactor = -1; 5134 } 5135 5136 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 5137 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5138 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 5139 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5140 return true; 5141 }; 5142 5143 SDValue N0 = N->getOperand(0); 5144 SDValue N1 = N->getOperand(1); 5145 5146 // Collect the shifts / magic values from each element. 5147 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5148 return SDValue(); 5149 5150 SDValue MagicFactor, Factor, Shift, ShiftMask; 5151 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5152 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5153 Factor = DAG.getBuildVector(VT, dl, Factors); 5154 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5155 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5156 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5157 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5158 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5159 "Expected matchUnaryPredicate to return one element for scalable " 5160 "vectors"); 5161 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5162 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5163 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5164 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5165 } else { 5166 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5167 MagicFactor = MagicFactors[0]; 5168 Factor = Factors[0]; 5169 Shift = Shifts[0]; 5170 ShiftMask = ShiftMasks[0]; 5171 } 5172 5173 // Multiply the numerator (operand 0) by the magic value. 5174 // FIXME: We should support doing a MUL in a wider type. 5175 auto GetMULHS = [&](SDValue X, SDValue Y) { 5176 // If the type isn't legal, use a wider mul of the the type calculated 5177 // earlier. 5178 if (!isTypeLegal(VT)) { 5179 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5180 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5181 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5182 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5183 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5184 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5185 } 5186 5187 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5188 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5189 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5190 SDValue LoHi = 5191 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5192 return SDValue(LoHi.getNode(), 1); 5193 } 5194 return SDValue(); 5195 }; 5196 5197 SDValue Q = GetMULHS(N0, MagicFactor); 5198 if (!Q) 5199 return SDValue(); 5200 5201 Created.push_back(Q.getNode()); 5202 5203 // (Optionally) Add/subtract the numerator using Factor. 5204 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5205 Created.push_back(Factor.getNode()); 5206 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5207 Created.push_back(Q.getNode()); 5208 5209 // Shift right algebraic by shift value. 5210 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5211 Created.push_back(Q.getNode()); 5212 5213 // Extract the sign bit, mask it and add it to the quotient. 5214 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5215 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5216 Created.push_back(T.getNode()); 5217 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5218 Created.push_back(T.getNode()); 5219 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5220 } 5221 5222 /// Given an ISD::UDIV node expressing a divide by constant, 5223 /// return a DAG expression to select that will generate the same value by 5224 /// multiplying by a magic number. 5225 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5226 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5227 bool IsAfterLegalization, 5228 SmallVectorImpl<SDNode *> &Created) const { 5229 SDLoc dl(N); 5230 EVT VT = N->getValueType(0); 5231 EVT SVT = VT.getScalarType(); 5232 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5233 EVT ShSVT = ShVT.getScalarType(); 5234 unsigned EltBits = VT.getScalarSizeInBits(); 5235 EVT MulVT; 5236 5237 // Check to see if we can do this. 5238 // FIXME: We should be more aggressive here. 5239 if (!isTypeLegal(VT)) { 5240 // Limit this to simple scalars for now. 5241 if (VT.isVector() || !VT.isSimple()) 5242 return SDValue(); 5243 5244 // If this type will be promoted to a large enough type with a legal 5245 // multiply operation, we can go ahead and do this transform. 5246 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5247 return SDValue(); 5248 5249 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5250 if (MulVT.getSizeInBits() < (2 * EltBits) || 5251 !isOperationLegal(ISD::MUL, MulVT)) 5252 return SDValue(); 5253 } 5254 5255 bool UseNPQ = false; 5256 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5257 5258 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5259 if (C->isNullValue()) 5260 return false; 5261 // FIXME: We should use a narrower constant when the upper 5262 // bits are known to be zero. 5263 const APInt& Divisor = C->getAPIntValue(); 5264 APInt::mu magics = Divisor.magicu(); 5265 unsigned PreShift = 0, PostShift = 0; 5266 5267 // If the divisor is even, we can avoid using the expensive fixup by 5268 // shifting the divided value upfront. 5269 if (magics.a != 0 && !Divisor[0]) { 5270 PreShift = Divisor.countTrailingZeros(); 5271 // Get magic number for the shifted divisor. 5272 magics = Divisor.lshr(PreShift).magicu(PreShift); 5273 assert(magics.a == 0 && "Should use cheap fixup now"); 5274 } 5275 5276 APInt Magic = magics.m; 5277 5278 unsigned SelNPQ; 5279 if (magics.a == 0 || Divisor.isOneValue()) { 5280 assert(magics.s < Divisor.getBitWidth() && 5281 "We shouldn't generate an undefined shift!"); 5282 PostShift = magics.s; 5283 SelNPQ = false; 5284 } else { 5285 PostShift = magics.s - 1; 5286 SelNPQ = true; 5287 } 5288 5289 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5290 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5291 NPQFactors.push_back( 5292 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5293 : APInt::getNullValue(EltBits), 5294 dl, SVT)); 5295 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5296 UseNPQ |= SelNPQ; 5297 return true; 5298 }; 5299 5300 SDValue N0 = N->getOperand(0); 5301 SDValue N1 = N->getOperand(1); 5302 5303 // Collect the shifts/magic values from each element. 5304 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5305 return SDValue(); 5306 5307 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5308 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5309 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5310 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5311 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5312 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5313 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5314 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5315 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5316 "Expected matchUnaryPredicate to return one for scalable vectors"); 5317 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5318 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5319 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5320 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5321 } else { 5322 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5323 PreShift = PreShifts[0]; 5324 MagicFactor = MagicFactors[0]; 5325 PostShift = PostShifts[0]; 5326 } 5327 5328 SDValue Q = N0; 5329 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5330 Created.push_back(Q.getNode()); 5331 5332 // FIXME: We should support doing a MUL in a wider type. 5333 auto GetMULHU = [&](SDValue X, SDValue Y) { 5334 // If the type isn't legal, use a wider mul of the the type calculated 5335 // earlier. 5336 if (!isTypeLegal(VT)) { 5337 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5338 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5339 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5340 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5341 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5342 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5343 } 5344 5345 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5346 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5347 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5348 SDValue LoHi = 5349 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5350 return SDValue(LoHi.getNode(), 1); 5351 } 5352 return SDValue(); // No mulhu or equivalent 5353 }; 5354 5355 // Multiply the numerator (operand 0) by the magic value. 5356 Q = GetMULHU(Q, MagicFactor); 5357 if (!Q) 5358 return SDValue(); 5359 5360 Created.push_back(Q.getNode()); 5361 5362 if (UseNPQ) { 5363 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5364 Created.push_back(NPQ.getNode()); 5365 5366 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5367 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5368 if (VT.isVector()) 5369 NPQ = GetMULHU(NPQ, NPQFactor); 5370 else 5371 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5372 5373 Created.push_back(NPQ.getNode()); 5374 5375 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5376 Created.push_back(Q.getNode()); 5377 } 5378 5379 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5380 Created.push_back(Q.getNode()); 5381 5382 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5383 5384 SDValue One = DAG.getConstant(1, dl, VT); 5385 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5386 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5387 } 5388 5389 /// If all values in Values that *don't* match the predicate are same 'splat' 5390 /// value, then replace all values with that splat value. 5391 /// Else, if AlternativeReplacement was provided, then replace all values that 5392 /// do match predicate with AlternativeReplacement value. 5393 static void 5394 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5395 std::function<bool(SDValue)> Predicate, 5396 SDValue AlternativeReplacement = SDValue()) { 5397 SDValue Replacement; 5398 // Is there a value for which the Predicate does *NOT* match? What is it? 5399 auto SplatValue = llvm::find_if_not(Values, Predicate); 5400 if (SplatValue != Values.end()) { 5401 // Does Values consist only of SplatValue's and values matching Predicate? 5402 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5403 return Value == *SplatValue || Predicate(Value); 5404 })) // Then we shall replace values matching predicate with SplatValue. 5405 Replacement = *SplatValue; 5406 } 5407 if (!Replacement) { 5408 // Oops, we did not find the "baseline" splat value. 5409 if (!AlternativeReplacement) 5410 return; // Nothing to do. 5411 // Let's replace with provided value then. 5412 Replacement = AlternativeReplacement; 5413 } 5414 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5415 } 5416 5417 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5418 /// where the divisor is constant and the comparison target is zero, 5419 /// return a DAG expression that will generate the same comparison result 5420 /// using only multiplications, additions and shifts/rotations. 5421 /// Ref: "Hacker's Delight" 10-17. 5422 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5423 SDValue CompTargetNode, 5424 ISD::CondCode Cond, 5425 DAGCombinerInfo &DCI, 5426 const SDLoc &DL) const { 5427 SmallVector<SDNode *, 5> Built; 5428 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5429 DCI, DL, Built)) { 5430 for (SDNode *N : Built) 5431 DCI.AddToWorklist(N); 5432 return Folded; 5433 } 5434 5435 return SDValue(); 5436 } 5437 5438 SDValue 5439 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5440 SDValue CompTargetNode, ISD::CondCode Cond, 5441 DAGCombinerInfo &DCI, const SDLoc &DL, 5442 SmallVectorImpl<SDNode *> &Created) const { 5443 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5444 // - D must be constant, with D = D0 * 2^K where D0 is odd 5445 // - P is the multiplicative inverse of D0 modulo 2^W 5446 // - Q = floor(((2^W) - 1) / D) 5447 // where W is the width of the common type of N and D. 5448 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5449 "Only applicable for (in)equality comparisons."); 5450 5451 SelectionDAG &DAG = DCI.DAG; 5452 5453 EVT VT = REMNode.getValueType(); 5454 EVT SVT = VT.getScalarType(); 5455 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5456 EVT ShSVT = ShVT.getScalarType(); 5457 5458 // If MUL is unavailable, we cannot proceed in any case. 5459 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5460 return SDValue(); 5461 5462 bool ComparingWithAllZeros = true; 5463 bool AllComparisonsWithNonZerosAreTautological = true; 5464 bool HadTautologicalLanes = false; 5465 bool AllLanesAreTautological = true; 5466 bool HadEvenDivisor = false; 5467 bool AllDivisorsArePowerOfTwo = true; 5468 bool HadTautologicalInvertedLanes = false; 5469 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 5470 5471 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 5472 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5473 if (CDiv->isNullValue()) 5474 return false; 5475 5476 const APInt &D = CDiv->getAPIntValue(); 5477 const APInt &Cmp = CCmp->getAPIntValue(); 5478 5479 ComparingWithAllZeros &= Cmp.isNullValue(); 5480 5481 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5482 // if C2 is not less than C1, the comparison is always false. 5483 // But we will only be able to produce the comparison that will give the 5484 // opposive tautological answer. So this lane would need to be fixed up. 5485 bool TautologicalInvertedLane = D.ule(Cmp); 5486 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 5487 5488 // If all lanes are tautological (either all divisors are ones, or divisor 5489 // is not greater than the constant we are comparing with), 5490 // we will prefer to avoid the fold. 5491 bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane; 5492 HadTautologicalLanes |= TautologicalLane; 5493 AllLanesAreTautological &= TautologicalLane; 5494 5495 // If we are comparing with non-zero, we need'll need to subtract said 5496 // comparison value from the LHS. But there is no point in doing that if 5497 // every lane where we are comparing with non-zero is tautological.. 5498 if (!Cmp.isNullValue()) 5499 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 5500 5501 // Decompose D into D0 * 2^K 5502 unsigned K = D.countTrailingZeros(); 5503 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5504 APInt D0 = D.lshr(K); 5505 5506 // D is even if it has trailing zeros. 5507 HadEvenDivisor |= (K != 0); 5508 // D is a power-of-two if D0 is one. 5509 // If all divisors are power-of-two, we will prefer to avoid the fold. 5510 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5511 5512 // P = inv(D0, 2^W) 5513 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5514 unsigned W = D.getBitWidth(); 5515 APInt P = D0.zext(W + 1) 5516 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5517 .trunc(W); 5518 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5519 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5520 5521 // Q = floor((2^W - 1) u/ D) 5522 // R = ((2^W - 1) u% D) 5523 APInt Q, R; 5524 APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R); 5525 5526 // If we are comparing with zero, then that comparison constant is okay, 5527 // else it may need to be one less than that. 5528 if (Cmp.ugt(R)) 5529 Q -= 1; 5530 5531 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5532 "We are expecting that K is always less than all-ones for ShSVT"); 5533 5534 // If the lane is tautological the result can be constant-folded. 5535 if (TautologicalLane) { 5536 // Set P and K amount to a bogus values so we can try to splat them. 5537 P = 0; 5538 K = -1; 5539 // And ensure that comparison constant is tautological, 5540 // it will always compare true/false. 5541 Q = -1; 5542 } 5543 5544 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5545 KAmts.push_back( 5546 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5547 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5548 return true; 5549 }; 5550 5551 SDValue N = REMNode.getOperand(0); 5552 SDValue D = REMNode.getOperand(1); 5553 5554 // Collect the values from each element. 5555 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 5556 return SDValue(); 5557 5558 // If all lanes are tautological, the result can be constant-folded. 5559 if (AllLanesAreTautological) 5560 return SDValue(); 5561 5562 // If this is a urem by a powers-of-two, avoid the fold since it can be 5563 // best implemented as a bit test. 5564 if (AllDivisorsArePowerOfTwo) 5565 return SDValue(); 5566 5567 SDValue PVal, KVal, QVal; 5568 if (VT.isVector()) { 5569 if (HadTautologicalLanes) { 5570 // Try to turn PAmts into a splat, since we don't care about the values 5571 // that are currently '0'. If we can't, just keep '0'`s. 5572 turnVectorIntoSplatVector(PAmts, isNullConstant); 5573 // Try to turn KAmts into a splat, since we don't care about the values 5574 // that are currently '-1'. If we can't, change them to '0'`s. 5575 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5576 DAG.getConstant(0, DL, ShSVT)); 5577 } 5578 5579 PVal = DAG.getBuildVector(VT, DL, PAmts); 5580 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5581 QVal = DAG.getBuildVector(VT, DL, QAmts); 5582 } else { 5583 PVal = PAmts[0]; 5584 KVal = KAmts[0]; 5585 QVal = QAmts[0]; 5586 } 5587 5588 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 5589 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 5590 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 5591 assert(CompTargetNode.getValueType() == N.getValueType() && 5592 "Expecting that the types on LHS and RHS of comparisons match."); 5593 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 5594 } 5595 5596 // (mul N, P) 5597 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5598 Created.push_back(Op0.getNode()); 5599 5600 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5601 // divisors as a performance improvement, since rotating by 0 is a no-op. 5602 if (HadEvenDivisor) { 5603 // We need ROTR to do this. 5604 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 5605 return SDValue(); 5606 SDNodeFlags Flags; 5607 Flags.setExact(true); 5608 // UREM: (rotr (mul N, P), K) 5609 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5610 Created.push_back(Op0.getNode()); 5611 } 5612 5613 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 5614 SDValue NewCC = 5615 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5616 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5617 if (!HadTautologicalInvertedLanes) 5618 return NewCC; 5619 5620 // If any lanes previously compared always-false, the NewCC will give 5621 // always-true result for them, so we need to fixup those lanes. 5622 // Or the other way around for inequality predicate. 5623 assert(VT.isVector() && "Can/should only get here for vectors."); 5624 Created.push_back(NewCC.getNode()); 5625 5626 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5627 // if C2 is not less than C1, the comparison is always false. 5628 // But we have produced the comparison that will give the 5629 // opposive tautological answer. So these lanes would need to be fixed up. 5630 SDValue TautologicalInvertedChannels = 5631 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 5632 Created.push_back(TautologicalInvertedChannels.getNode()); 5633 5634 // NOTE: we avoid letting illegal types through even if we're before legalize 5635 // ops – legalization has a hard time producing good code for this. 5636 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 5637 // If we have a vector select, let's replace the comparison results in the 5638 // affected lanes with the correct tautological result. 5639 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 5640 DL, SETCCVT, SETCCVT); 5641 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 5642 Replacement, NewCC); 5643 } 5644 5645 // Else, we can just invert the comparison result in the appropriate lanes. 5646 // 5647 // NOTE: see the note above VSELECT above. 5648 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 5649 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 5650 TautologicalInvertedChannels); 5651 5652 return SDValue(); // Don't know how to lower. 5653 } 5654 5655 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 5656 /// where the divisor is constant and the comparison target is zero, 5657 /// return a DAG expression that will generate the same comparison result 5658 /// using only multiplications, additions and shifts/rotations. 5659 /// Ref: "Hacker's Delight" 10-17. 5660 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 5661 SDValue CompTargetNode, 5662 ISD::CondCode Cond, 5663 DAGCombinerInfo &DCI, 5664 const SDLoc &DL) const { 5665 SmallVector<SDNode *, 7> Built; 5666 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5667 DCI, DL, Built)) { 5668 assert(Built.size() <= 7 && "Max size prediction failed."); 5669 for (SDNode *N : Built) 5670 DCI.AddToWorklist(N); 5671 return Folded; 5672 } 5673 5674 return SDValue(); 5675 } 5676 5677 SDValue 5678 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 5679 SDValue CompTargetNode, ISD::CondCode Cond, 5680 DAGCombinerInfo &DCI, const SDLoc &DL, 5681 SmallVectorImpl<SDNode *> &Created) const { 5682 // Fold: 5683 // (seteq/ne (srem N, D), 0) 5684 // To: 5685 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 5686 // 5687 // - D must be constant, with D = D0 * 2^K where D0 is odd 5688 // - P is the multiplicative inverse of D0 modulo 2^W 5689 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 5690 // - Q = floor((2 * A) / (2^K)) 5691 // where W is the width of the common type of N and D. 5692 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5693 "Only applicable for (in)equality comparisons."); 5694 5695 SelectionDAG &DAG = DCI.DAG; 5696 5697 EVT VT = REMNode.getValueType(); 5698 EVT SVT = VT.getScalarType(); 5699 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5700 EVT ShSVT = ShVT.getScalarType(); 5701 5702 // If we are after ops legalization, and MUL is unavailable, we can not 5703 // proceed. 5704 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5705 return SDValue(); 5706 5707 // TODO: Could support comparing with non-zero too. 5708 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 5709 if (!CompTarget || !CompTarget->isNullValue()) 5710 return SDValue(); 5711 5712 bool HadIntMinDivisor = false; 5713 bool HadOneDivisor = false; 5714 bool AllDivisorsAreOnes = true; 5715 bool HadEvenDivisor = false; 5716 bool NeedToApplyOffset = false; 5717 bool AllDivisorsArePowerOfTwo = true; 5718 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 5719 5720 auto BuildSREMPattern = [&](ConstantSDNode *C) { 5721 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5722 if (C->isNullValue()) 5723 return false; 5724 5725 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 5726 5727 // WARNING: this fold is only valid for positive divisors! 5728 APInt D = C->getAPIntValue(); 5729 if (D.isNegative()) 5730 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 5731 5732 HadIntMinDivisor |= D.isMinSignedValue(); 5733 5734 // If all divisors are ones, we will prefer to avoid the fold. 5735 HadOneDivisor |= D.isOneValue(); 5736 AllDivisorsAreOnes &= D.isOneValue(); 5737 5738 // Decompose D into D0 * 2^K 5739 unsigned K = D.countTrailingZeros(); 5740 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5741 APInt D0 = D.lshr(K); 5742 5743 if (!D.isMinSignedValue()) { 5744 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 5745 // we don't care about this lane in this fold, we'll special-handle it. 5746 HadEvenDivisor |= (K != 0); 5747 } 5748 5749 // D is a power-of-two if D0 is one. This includes INT_MIN. 5750 // If all divisors are power-of-two, we will prefer to avoid the fold. 5751 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5752 5753 // P = inv(D0, 2^W) 5754 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5755 unsigned W = D.getBitWidth(); 5756 APInt P = D0.zext(W + 1) 5757 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5758 .trunc(W); 5759 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5760 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5761 5762 // A = floor((2^(W - 1) - 1) / D0) & -2^K 5763 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 5764 A.clearLowBits(K); 5765 5766 if (!D.isMinSignedValue()) { 5767 // If divisor INT_MIN, then we don't care about this lane in this fold, 5768 // we'll special-handle it. 5769 NeedToApplyOffset |= A != 0; 5770 } 5771 5772 // Q = floor((2 * A) / (2^K)) 5773 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 5774 5775 assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) && 5776 "We are expecting that A is always less than all-ones for SVT"); 5777 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5778 "We are expecting that K is always less than all-ones for ShSVT"); 5779 5780 // If the divisor is 1 the result can be constant-folded. Likewise, we 5781 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 5782 if (D.isOneValue()) { 5783 // Set P, A and K to a bogus values so we can try to splat them. 5784 P = 0; 5785 A = -1; 5786 K = -1; 5787 5788 // x ?% 1 == 0 <--> true <--> x u<= -1 5789 Q = -1; 5790 } 5791 5792 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5793 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 5794 KAmts.push_back( 5795 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5796 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5797 return true; 5798 }; 5799 5800 SDValue N = REMNode.getOperand(0); 5801 SDValue D = REMNode.getOperand(1); 5802 5803 // Collect the values from each element. 5804 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 5805 return SDValue(); 5806 5807 // If this is a srem by a one, avoid the fold since it can be constant-folded. 5808 if (AllDivisorsAreOnes) 5809 return SDValue(); 5810 5811 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 5812 // since it can be best implemented as a bit test. 5813 if (AllDivisorsArePowerOfTwo) 5814 return SDValue(); 5815 5816 SDValue PVal, AVal, KVal, QVal; 5817 if (D.getOpcode() == ISD::BUILD_VECTOR) { 5818 if (HadOneDivisor) { 5819 // Try to turn PAmts into a splat, since we don't care about the values 5820 // that are currently '0'. If we can't, just keep '0'`s. 5821 turnVectorIntoSplatVector(PAmts, isNullConstant); 5822 // Try to turn AAmts into a splat, since we don't care about the 5823 // values that are currently '-1'. If we can't, change them to '0'`s. 5824 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 5825 DAG.getConstant(0, DL, SVT)); 5826 // Try to turn KAmts into a splat, since we don't care about the values 5827 // that are currently '-1'. If we can't, change them to '0'`s. 5828 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5829 DAG.getConstant(0, DL, ShSVT)); 5830 } 5831 5832 PVal = DAG.getBuildVector(VT, DL, PAmts); 5833 AVal = DAG.getBuildVector(VT, DL, AAmts); 5834 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5835 QVal = DAG.getBuildVector(VT, DL, QAmts); 5836 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 5837 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 5838 QAmts.size() == 1 && 5839 "Expected matchUnaryPredicate to return one element for scalable " 5840 "vectors"); 5841 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 5842 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 5843 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 5844 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 5845 } else { 5846 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 5847 PVal = PAmts[0]; 5848 AVal = AAmts[0]; 5849 KVal = KAmts[0]; 5850 QVal = QAmts[0]; 5851 } 5852 5853 // (mul N, P) 5854 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5855 Created.push_back(Op0.getNode()); 5856 5857 if (NeedToApplyOffset) { 5858 // We need ADD to do this. 5859 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 5860 return SDValue(); 5861 5862 // (add (mul N, P), A) 5863 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 5864 Created.push_back(Op0.getNode()); 5865 } 5866 5867 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5868 // divisors as a performance improvement, since rotating by 0 is a no-op. 5869 if (HadEvenDivisor) { 5870 // We need ROTR to do this. 5871 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 5872 return SDValue(); 5873 SDNodeFlags Flags; 5874 Flags.setExact(true); 5875 // SREM: (rotr (add (mul N, P), A), K) 5876 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5877 Created.push_back(Op0.getNode()); 5878 } 5879 5880 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 5881 SDValue Fold = 5882 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5883 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5884 5885 // If we didn't have lanes with INT_MIN divisor, then we're done. 5886 if (!HadIntMinDivisor) 5887 return Fold; 5888 5889 // That fold is only valid for positive divisors. Which effectively means, 5890 // it is invalid for INT_MIN divisors. So if we have such a lane, 5891 // we must fix-up results for said lanes. 5892 assert(VT.isVector() && "Can/should only get here for vectors."); 5893 5894 // NOTE: we avoid letting illegal types through even if we're before legalize 5895 // ops – legalization has a hard time producing good code for the code that 5896 // follows. 5897 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 5898 !isOperationLegalOrCustom(ISD::AND, VT) || 5899 !isOperationLegalOrCustom(Cond, VT) || 5900 !isOperationLegalOrCustom(ISD::VSELECT, VT)) 5901 return SDValue(); 5902 5903 Created.push_back(Fold.getNode()); 5904 5905 SDValue IntMin = DAG.getConstant( 5906 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 5907 SDValue IntMax = DAG.getConstant( 5908 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 5909 SDValue Zero = 5910 DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT); 5911 5912 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 5913 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 5914 Created.push_back(DivisorIsIntMin.getNode()); 5915 5916 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 5917 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 5918 Created.push_back(Masked.getNode()); 5919 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 5920 Created.push_back(MaskedIsZero.getNode()); 5921 5922 // To produce final result we need to blend 2 vectors: 'SetCC' and 5923 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 5924 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 5925 // constant-folded, select can get lowered to a shuffle with constant mask. 5926 SDValue Blended = 5927 DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold); 5928 5929 return Blended; 5930 } 5931 5932 bool TargetLowering:: 5933 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 5934 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 5935 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 5936 "be a constant integer"); 5937 return true; 5938 } 5939 5940 return false; 5941 } 5942 5943 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 5944 const DenormalMode &Mode) const { 5945 SDLoc DL(Op); 5946 EVT VT = Op.getValueType(); 5947 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5948 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5949 // Testing it with denormal inputs to avoid wrong estimate. 5950 if (Mode.Input == DenormalMode::IEEE) { 5951 // This is specifically a check for the handling of denormal inputs, 5952 // not the result. 5953 5954 // Test = fabs(X) < SmallestNormal 5955 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 5956 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 5957 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 5958 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 5959 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 5960 } 5961 // Test = X == 0.0 5962 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 5963 } 5964 5965 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 5966 bool LegalOps, bool OptForSize, 5967 NegatibleCost &Cost, 5968 unsigned Depth) const { 5969 // fneg is removable even if it has multiple uses. 5970 if (Op.getOpcode() == ISD::FNEG) { 5971 Cost = NegatibleCost::Cheaper; 5972 return Op.getOperand(0); 5973 } 5974 5975 // Don't recurse exponentially. 5976 if (Depth > SelectionDAG::MaxRecursionDepth) 5977 return SDValue(); 5978 5979 // Pre-increment recursion depth for use in recursive calls. 5980 ++Depth; 5981 const SDNodeFlags Flags = Op->getFlags(); 5982 const TargetOptions &Options = DAG.getTarget().Options; 5983 EVT VT = Op.getValueType(); 5984 unsigned Opcode = Op.getOpcode(); 5985 5986 // Don't allow anything with multiple uses unless we know it is free. 5987 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 5988 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 5989 isFPExtFree(VT, Op.getOperand(0).getValueType()); 5990 if (!IsFreeExtend) 5991 return SDValue(); 5992 } 5993 5994 auto RemoveDeadNode = [&](SDValue N) { 5995 if (N && N.getNode()->use_empty()) 5996 DAG.RemoveDeadNode(N.getNode()); 5997 }; 5998 5999 SDLoc DL(Op); 6000 6001 // Because getNegatedExpression can delete nodes we need a handle to keep 6002 // temporary nodes alive in case the recursion manages to create an identical 6003 // node. 6004 std::list<HandleSDNode> Handles; 6005 6006 switch (Opcode) { 6007 case ISD::ConstantFP: { 6008 // Don't invert constant FP values after legalization unless the target says 6009 // the negated constant is legal. 6010 bool IsOpLegal = 6011 isOperationLegal(ISD::ConstantFP, VT) || 6012 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6013 OptForSize); 6014 6015 if (LegalOps && !IsOpLegal) 6016 break; 6017 6018 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6019 V.changeSign(); 6020 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6021 6022 // If we already have the use of the negated floating constant, it is free 6023 // to negate it even it has multiple uses. 6024 if (!Op.hasOneUse() && CFP.use_empty()) 6025 break; 6026 Cost = NegatibleCost::Neutral; 6027 return CFP; 6028 } 6029 case ISD::BUILD_VECTOR: { 6030 // Only permit BUILD_VECTOR of constants. 6031 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6032 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6033 })) 6034 break; 6035 6036 bool IsOpLegal = 6037 (isOperationLegal(ISD::ConstantFP, VT) && 6038 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6039 llvm::all_of(Op->op_values(), [&](SDValue N) { 6040 return N.isUndef() || 6041 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6042 OptForSize); 6043 }); 6044 6045 if (LegalOps && !IsOpLegal) 6046 break; 6047 6048 SmallVector<SDValue, 4> Ops; 6049 for (SDValue C : Op->op_values()) { 6050 if (C.isUndef()) { 6051 Ops.push_back(C); 6052 continue; 6053 } 6054 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6055 V.changeSign(); 6056 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6057 } 6058 Cost = NegatibleCost::Neutral; 6059 return DAG.getBuildVector(VT, DL, Ops); 6060 } 6061 case ISD::FADD: { 6062 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6063 break; 6064 6065 // After operation legalization, it might not be legal to create new FSUBs. 6066 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6067 break; 6068 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6069 6070 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6071 NegatibleCost CostX = NegatibleCost::Expensive; 6072 SDValue NegX = 6073 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6074 // Prevent this node from being deleted by the next call. 6075 if (NegX) 6076 Handles.emplace_back(NegX); 6077 6078 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6079 NegatibleCost CostY = NegatibleCost::Expensive; 6080 SDValue NegY = 6081 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6082 6083 // We're done with the handles. 6084 Handles.clear(); 6085 6086 // Negate the X if its cost is less or equal than Y. 6087 if (NegX && (CostX <= CostY)) { 6088 Cost = CostX; 6089 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6090 if (NegY != N) 6091 RemoveDeadNode(NegY); 6092 return N; 6093 } 6094 6095 // Negate the Y if it is not expensive. 6096 if (NegY) { 6097 Cost = CostY; 6098 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6099 if (NegX != N) 6100 RemoveDeadNode(NegX); 6101 return N; 6102 } 6103 break; 6104 } 6105 case ISD::FSUB: { 6106 // We can't turn -(A-B) into B-A when we honor signed zeros. 6107 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6108 break; 6109 6110 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6111 // fold (fneg (fsub 0, Y)) -> Y 6112 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6113 if (C->isZero()) { 6114 Cost = NegatibleCost::Cheaper; 6115 return Y; 6116 } 6117 6118 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6119 Cost = NegatibleCost::Neutral; 6120 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6121 } 6122 case ISD::FMUL: 6123 case ISD::FDIV: { 6124 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6125 6126 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6127 NegatibleCost CostX = NegatibleCost::Expensive; 6128 SDValue NegX = 6129 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6130 // Prevent this node from being deleted by the next call. 6131 if (NegX) 6132 Handles.emplace_back(NegX); 6133 6134 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6135 NegatibleCost CostY = NegatibleCost::Expensive; 6136 SDValue NegY = 6137 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6138 6139 // We're done with the handles. 6140 Handles.clear(); 6141 6142 // Negate the X if its cost is less or equal than Y. 6143 if (NegX && (CostX <= CostY)) { 6144 Cost = CostX; 6145 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6146 if (NegY != N) 6147 RemoveDeadNode(NegY); 6148 return N; 6149 } 6150 6151 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6152 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6153 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6154 break; 6155 6156 // Negate the Y if it is not expensive. 6157 if (NegY) { 6158 Cost = CostY; 6159 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6160 if (NegX != N) 6161 RemoveDeadNode(NegX); 6162 return N; 6163 } 6164 break; 6165 } 6166 case ISD::FMA: 6167 case ISD::FMAD: { 6168 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6169 break; 6170 6171 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6172 NegatibleCost CostZ = NegatibleCost::Expensive; 6173 SDValue NegZ = 6174 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6175 // Give up if fail to negate the Z. 6176 if (!NegZ) 6177 break; 6178 6179 // Prevent this node from being deleted by the next two calls. 6180 Handles.emplace_back(NegZ); 6181 6182 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6183 NegatibleCost CostX = NegatibleCost::Expensive; 6184 SDValue NegX = 6185 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6186 // Prevent this node from being deleted by the next call. 6187 if (NegX) 6188 Handles.emplace_back(NegX); 6189 6190 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6191 NegatibleCost CostY = NegatibleCost::Expensive; 6192 SDValue NegY = 6193 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6194 6195 // We're done with the handles. 6196 Handles.clear(); 6197 6198 // Negate the X if its cost is less or equal than Y. 6199 if (NegX && (CostX <= CostY)) { 6200 Cost = std::min(CostX, CostZ); 6201 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6202 if (NegY != N) 6203 RemoveDeadNode(NegY); 6204 return N; 6205 } 6206 6207 // Negate the Y if it is not expensive. 6208 if (NegY) { 6209 Cost = std::min(CostY, CostZ); 6210 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6211 if (NegX != N) 6212 RemoveDeadNode(NegX); 6213 return N; 6214 } 6215 break; 6216 } 6217 6218 case ISD::FP_EXTEND: 6219 case ISD::FSIN: 6220 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6221 OptForSize, Cost, Depth)) 6222 return DAG.getNode(Opcode, DL, VT, NegV); 6223 break; 6224 case ISD::FP_ROUND: 6225 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6226 OptForSize, Cost, Depth)) 6227 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6228 break; 6229 } 6230 6231 return SDValue(); 6232 } 6233 6234 //===----------------------------------------------------------------------===// 6235 // Legalization Utilities 6236 //===----------------------------------------------------------------------===// 6237 6238 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6239 SDValue LHS, SDValue RHS, 6240 SmallVectorImpl<SDValue> &Result, 6241 EVT HiLoVT, SelectionDAG &DAG, 6242 MulExpansionKind Kind, SDValue LL, 6243 SDValue LH, SDValue RL, SDValue RH) const { 6244 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6245 Opcode == ISD::SMUL_LOHI); 6246 6247 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6248 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6249 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6250 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6251 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6252 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6253 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6254 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6255 6256 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6257 return false; 6258 6259 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6260 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6261 6262 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6263 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6264 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6265 6266 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6267 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6268 bool Signed) -> bool { 6269 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6270 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6271 Hi = SDValue(Lo.getNode(), 1); 6272 return true; 6273 } 6274 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6275 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6276 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6277 return true; 6278 } 6279 return false; 6280 }; 6281 6282 SDValue Lo, Hi; 6283 6284 if (!LL.getNode() && !RL.getNode() && 6285 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6286 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6287 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6288 } 6289 6290 if (!LL.getNode()) 6291 return false; 6292 6293 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6294 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6295 DAG.MaskedValueIsZero(RHS, HighMask)) { 6296 // The inputs are both zero-extended. 6297 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6298 Result.push_back(Lo); 6299 Result.push_back(Hi); 6300 if (Opcode != ISD::MUL) { 6301 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6302 Result.push_back(Zero); 6303 Result.push_back(Zero); 6304 } 6305 return true; 6306 } 6307 } 6308 6309 if (!VT.isVector() && Opcode == ISD::MUL && 6310 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6311 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6312 // The input values are both sign-extended. 6313 // TODO non-MUL case? 6314 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6315 Result.push_back(Lo); 6316 Result.push_back(Hi); 6317 return true; 6318 } 6319 } 6320 6321 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6322 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6323 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 6324 // FIXME getShiftAmountTy does not always return a sensible result when VT 6325 // is an illegal type, and so the type may be too small to fit the shift 6326 // amount. Override it with i32. The shift will have to be legalized. 6327 ShiftAmountTy = MVT::i32; 6328 } 6329 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6330 6331 if (!LH.getNode() && !RH.getNode() && 6332 isOperationLegalOrCustom(ISD::SRL, VT) && 6333 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6334 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6335 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6336 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6337 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6338 } 6339 6340 if (!LH.getNode()) 6341 return false; 6342 6343 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6344 return false; 6345 6346 Result.push_back(Lo); 6347 6348 if (Opcode == ISD::MUL) { 6349 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6350 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6351 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6352 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6353 Result.push_back(Hi); 6354 return true; 6355 } 6356 6357 // Compute the full width result. 6358 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6359 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6360 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6361 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6362 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6363 }; 6364 6365 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6366 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6367 return false; 6368 6369 // This is effectively the add part of a multiply-add of half-sized operands, 6370 // so it cannot overflow. 6371 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6372 6373 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6374 return false; 6375 6376 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6377 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6378 6379 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6380 isOperationLegalOrCustom(ISD::ADDE, VT)); 6381 if (UseGlue) 6382 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6383 Merge(Lo, Hi)); 6384 else 6385 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6386 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6387 6388 SDValue Carry = Next.getValue(1); 6389 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6390 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6391 6392 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6393 return false; 6394 6395 if (UseGlue) 6396 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6397 Carry); 6398 else 6399 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6400 Zero, Carry); 6401 6402 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6403 6404 if (Opcode == ISD::SMUL_LOHI) { 6405 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6406 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6407 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6408 6409 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6410 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6411 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6412 } 6413 6414 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6415 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6416 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6417 return true; 6418 } 6419 6420 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6421 SelectionDAG &DAG, MulExpansionKind Kind, 6422 SDValue LL, SDValue LH, SDValue RL, 6423 SDValue RH) const { 6424 SmallVector<SDValue, 2> Result; 6425 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6426 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6427 DAG, Kind, LL, LH, RL, RH); 6428 if (Ok) { 6429 assert(Result.size() == 2); 6430 Lo = Result[0]; 6431 Hi = Result[1]; 6432 } 6433 return Ok; 6434 } 6435 6436 // Check that (every element of) Z is undef or not an exact multiple of BW. 6437 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6438 return ISD::matchUnaryPredicate( 6439 Z, 6440 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6441 true); 6442 } 6443 6444 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 6445 SelectionDAG &DAG) const { 6446 EVT VT = Node->getValueType(0); 6447 6448 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6449 !isOperationLegalOrCustom(ISD::SRL, VT) || 6450 !isOperationLegalOrCustom(ISD::SUB, VT) || 6451 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6452 return false; 6453 6454 SDValue X = Node->getOperand(0); 6455 SDValue Y = Node->getOperand(1); 6456 SDValue Z = Node->getOperand(2); 6457 6458 unsigned BW = VT.getScalarSizeInBits(); 6459 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6460 SDLoc DL(SDValue(Node, 0)); 6461 6462 EVT ShVT = Z.getValueType(); 6463 6464 // If a funnel shift in the other direction is more supported, use it. 6465 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6466 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6467 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6468 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6469 // fshl X, Y, Z -> fshr X, Y, -Z 6470 // fshr X, Y, Z -> fshl X, Y, -Z 6471 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6472 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 6473 } else { 6474 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 6475 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 6476 SDValue One = DAG.getConstant(1, DL, ShVT); 6477 if (IsFSHL) { 6478 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6479 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 6480 } else { 6481 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6482 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 6483 } 6484 Z = DAG.getNOT(DL, Z, ShVT); 6485 } 6486 Result = DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 6487 return true; 6488 } 6489 6490 SDValue ShX, ShY; 6491 SDValue ShAmt, InvShAmt; 6492 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6493 // fshl: X << C | Y >> (BW - C) 6494 // fshr: X << (BW - C) | Y >> C 6495 // where C = Z % BW is not zero 6496 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6497 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6498 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 6499 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 6500 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6501 } else { 6502 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 6503 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 6504 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 6505 if (isPowerOf2_32(BW)) { 6506 // Z % BW -> Z & (BW - 1) 6507 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 6508 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 6509 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 6510 } else { 6511 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6512 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6513 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 6514 } 6515 6516 SDValue One = DAG.getConstant(1, DL, ShVT); 6517 if (IsFSHL) { 6518 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 6519 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 6520 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 6521 } else { 6522 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 6523 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 6524 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 6525 } 6526 } 6527 Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 6528 return true; 6529 } 6530 6531 // TODO: Merge with expandFunnelShift. 6532 bool TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 6533 SDValue &Result, SelectionDAG &DAG) const { 6534 EVT VT = Node->getValueType(0); 6535 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6536 bool IsLeft = Node->getOpcode() == ISD::ROTL; 6537 SDValue Op0 = Node->getOperand(0); 6538 SDValue Op1 = Node->getOperand(1); 6539 SDLoc DL(SDValue(Node, 0)); 6540 6541 EVT ShVT = Op1.getValueType(); 6542 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6543 6544 // If a rotate in the other direction is supported, use it. 6545 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 6546 if (isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 6547 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6548 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 6549 return true; 6550 } 6551 6552 if (!AllowVectorOps && VT.isVector() && 6553 (!isOperationLegalOrCustom(ISD::SHL, VT) || 6554 !isOperationLegalOrCustom(ISD::SRL, VT) || 6555 !isOperationLegalOrCustom(ISD::SUB, VT) || 6556 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 6557 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6558 return false; 6559 6560 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 6561 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 6562 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 6563 SDValue ShVal; 6564 SDValue HsVal; 6565 if (isPowerOf2_32(EltSizeInBits)) { 6566 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 6567 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 6568 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6569 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 6570 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6571 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 6572 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 6573 } else { 6574 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 6575 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 6576 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 6577 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 6578 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6579 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 6580 SDValue One = DAG.getConstant(1, DL, ShVT); 6581 HsVal = 6582 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 6583 } 6584 Result = DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 6585 return true; 6586 } 6587 6588 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 6589 SelectionDAG &DAG) const { 6590 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6591 SDValue Src = Node->getOperand(OpNo); 6592 EVT SrcVT = Src.getValueType(); 6593 EVT DstVT = Node->getValueType(0); 6594 SDLoc dl(SDValue(Node, 0)); 6595 6596 // FIXME: Only f32 to i64 conversions are supported. 6597 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 6598 return false; 6599 6600 if (Node->isStrictFPOpcode()) 6601 // When a NaN is converted to an integer a trap is allowed. We can't 6602 // use this expansion here because it would eliminate that trap. Other 6603 // traps are also allowed and cannot be eliminated. See 6604 // IEEE 754-2008 sec 5.8. 6605 return false; 6606 6607 // Expand f32 -> i64 conversion 6608 // This algorithm comes from compiler-rt's implementation of fixsfdi: 6609 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 6610 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 6611 EVT IntVT = SrcVT.changeTypeToInteger(); 6612 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 6613 6614 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 6615 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 6616 SDValue Bias = DAG.getConstant(127, dl, IntVT); 6617 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 6618 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 6619 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 6620 6621 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 6622 6623 SDValue ExponentBits = DAG.getNode( 6624 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 6625 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 6626 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 6627 6628 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 6629 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 6630 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 6631 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 6632 6633 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 6634 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 6635 DAG.getConstant(0x00800000, dl, IntVT)); 6636 6637 R = DAG.getZExtOrTrunc(R, dl, DstVT); 6638 6639 R = DAG.getSelectCC( 6640 dl, Exponent, ExponentLoBit, 6641 DAG.getNode(ISD::SHL, dl, DstVT, R, 6642 DAG.getZExtOrTrunc( 6643 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 6644 dl, IntShVT)), 6645 DAG.getNode(ISD::SRL, dl, DstVT, R, 6646 DAG.getZExtOrTrunc( 6647 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 6648 dl, IntShVT)), 6649 ISD::SETGT); 6650 6651 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 6652 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 6653 6654 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 6655 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 6656 return true; 6657 } 6658 6659 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 6660 SDValue &Chain, 6661 SelectionDAG &DAG) const { 6662 SDLoc dl(SDValue(Node, 0)); 6663 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6664 SDValue Src = Node->getOperand(OpNo); 6665 6666 EVT SrcVT = Src.getValueType(); 6667 EVT DstVT = Node->getValueType(0); 6668 EVT SetCCVT = 6669 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 6670 EVT DstSetCCVT = 6671 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 6672 6673 // Only expand vector types if we have the appropriate vector bit operations. 6674 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 6675 ISD::FP_TO_SINT; 6676 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 6677 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 6678 return false; 6679 6680 // If the maximum float value is smaller then the signed integer range, 6681 // the destination signmask can't be represented by the float, so we can 6682 // just use FP_TO_SINT directly. 6683 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 6684 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 6685 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 6686 if (APFloat::opOverflow & 6687 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 6688 if (Node->isStrictFPOpcode()) { 6689 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6690 { Node->getOperand(0), Src }); 6691 Chain = Result.getValue(1); 6692 } else 6693 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6694 return true; 6695 } 6696 6697 // Don't expand it if there isn't cheap fsub instruction. 6698 if (!isOperationLegalOrCustom( 6699 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 6700 return false; 6701 6702 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 6703 SDValue Sel; 6704 6705 if (Node->isStrictFPOpcode()) { 6706 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 6707 Node->getOperand(0), /*IsSignaling*/ true); 6708 Chain = Sel.getValue(1); 6709 } else { 6710 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 6711 } 6712 6713 bool Strict = Node->isStrictFPOpcode() || 6714 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 6715 6716 if (Strict) { 6717 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 6718 // signmask then offset (the result of which should be fully representable). 6719 // Sel = Src < 0x8000000000000000 6720 // FltOfs = select Sel, 0, 0x8000000000000000 6721 // IntOfs = select Sel, 0, 0x8000000000000000 6722 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 6723 6724 // TODO: Should any fast-math-flags be set for the FSUB? 6725 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 6726 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 6727 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6728 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 6729 DAG.getConstant(0, dl, DstVT), 6730 DAG.getConstant(SignMask, dl, DstVT)); 6731 SDValue SInt; 6732 if (Node->isStrictFPOpcode()) { 6733 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 6734 { Chain, Src, FltOfs }); 6735 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6736 { Val.getValue(1), Val }); 6737 Chain = SInt.getValue(1); 6738 } else { 6739 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 6740 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 6741 } 6742 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 6743 } else { 6744 // Expand based on maximum range of FP_TO_SINT: 6745 // True = fp_to_sint(Src) 6746 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 6747 // Result = select (Src < 0x8000000000000000), True, False 6748 6749 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6750 // TODO: Should any fast-math-flags be set for the FSUB? 6751 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 6752 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 6753 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 6754 DAG.getConstant(SignMask, dl, DstVT)); 6755 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6756 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 6757 } 6758 return true; 6759 } 6760 6761 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 6762 SDValue &Chain, 6763 SelectionDAG &DAG) const { 6764 // This transform is not correct for converting 0 when rounding mode is set 6765 // to round toward negative infinity which will produce -0.0. So disable under 6766 // strictfp. 6767 if (Node->isStrictFPOpcode()) 6768 return false; 6769 6770 SDValue Src = Node->getOperand(0); 6771 EVT SrcVT = Src.getValueType(); 6772 EVT DstVT = Node->getValueType(0); 6773 6774 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 6775 return false; 6776 6777 // Only expand vector types if we have the appropriate vector bit operations. 6778 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 6779 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 6780 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 6781 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 6782 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 6783 return false; 6784 6785 SDLoc dl(SDValue(Node, 0)); 6786 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 6787 6788 // Implementation of unsigned i64 to f64 following the algorithm in 6789 // __floatundidf in compiler_rt. This implementation performs rounding 6790 // correctly in all rounding modes with the exception of converting 0 6791 // when rounding toward negative infinity. In that case the fsub will produce 6792 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 6793 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 6794 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 6795 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 6796 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 6797 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 6798 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 6799 6800 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 6801 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 6802 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 6803 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 6804 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 6805 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 6806 SDValue HiSub = 6807 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 6808 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 6809 return true; 6810 } 6811 6812 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 6813 SelectionDAG &DAG) const { 6814 SDLoc dl(Node); 6815 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 6816 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 6817 EVT VT = Node->getValueType(0); 6818 6819 if (VT.isScalableVector()) 6820 report_fatal_error( 6821 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 6822 6823 if (isOperationLegalOrCustom(NewOp, VT)) { 6824 SDValue Quiet0 = Node->getOperand(0); 6825 SDValue Quiet1 = Node->getOperand(1); 6826 6827 if (!Node->getFlags().hasNoNaNs()) { 6828 // Insert canonicalizes if it's possible we need to quiet to get correct 6829 // sNaN behavior. 6830 if (!DAG.isKnownNeverSNaN(Quiet0)) { 6831 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 6832 Node->getFlags()); 6833 } 6834 if (!DAG.isKnownNeverSNaN(Quiet1)) { 6835 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 6836 Node->getFlags()); 6837 } 6838 } 6839 6840 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 6841 } 6842 6843 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 6844 // instead if there are no NaNs. 6845 if (Node->getFlags().hasNoNaNs()) { 6846 unsigned IEEE2018Op = 6847 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 6848 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 6849 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 6850 Node->getOperand(1), Node->getFlags()); 6851 } 6852 } 6853 6854 // If none of the above worked, but there are no NaNs, then expand to 6855 // a compare/select sequence. This is required for correctness since 6856 // InstCombine might have canonicalized a fcmp+select sequence to a 6857 // FMINNUM/FMAXNUM node. If we were to fall through to the default 6858 // expansion to libcall, we might introduce a link-time dependency 6859 // on libm into a file that originally did not have one. 6860 if (Node->getFlags().hasNoNaNs()) { 6861 ISD::CondCode Pred = 6862 Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 6863 SDValue Op1 = Node->getOperand(0); 6864 SDValue Op2 = Node->getOperand(1); 6865 SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred); 6866 // Copy FMF flags, but always set the no-signed-zeros flag 6867 // as this is implied by the FMINNUM/FMAXNUM semantics. 6868 SDNodeFlags Flags = Node->getFlags(); 6869 Flags.setNoSignedZeros(true); 6870 SelCC->setFlags(Flags); 6871 return SelCC; 6872 } 6873 6874 return SDValue(); 6875 } 6876 6877 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 6878 SelectionDAG &DAG) const { 6879 SDLoc dl(Node); 6880 EVT VT = Node->getValueType(0); 6881 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6882 SDValue Op = Node->getOperand(0); 6883 unsigned Len = VT.getScalarSizeInBits(); 6884 assert(VT.isInteger() && "CTPOP not implemented for this type."); 6885 6886 // TODO: Add support for irregular type lengths. 6887 if (!(Len <= 128 && Len % 8 == 0)) 6888 return false; 6889 6890 // Only expand vector types if we have the appropriate vector bit operations. 6891 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 6892 !isOperationLegalOrCustom(ISD::SUB, VT) || 6893 !isOperationLegalOrCustom(ISD::SRL, VT) || 6894 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 6895 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6896 return false; 6897 6898 // This is the "best" algorithm from 6899 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 6900 SDValue Mask55 = 6901 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 6902 SDValue Mask33 = 6903 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 6904 SDValue Mask0F = 6905 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 6906 SDValue Mask01 = 6907 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 6908 6909 // v = v - ((v >> 1) & 0x55555555...) 6910 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 6911 DAG.getNode(ISD::AND, dl, VT, 6912 DAG.getNode(ISD::SRL, dl, VT, Op, 6913 DAG.getConstant(1, dl, ShVT)), 6914 Mask55)); 6915 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 6916 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 6917 DAG.getNode(ISD::AND, dl, VT, 6918 DAG.getNode(ISD::SRL, dl, VT, Op, 6919 DAG.getConstant(2, dl, ShVT)), 6920 Mask33)); 6921 // v = (v + (v >> 4)) & 0x0F0F0F0F... 6922 Op = DAG.getNode(ISD::AND, dl, VT, 6923 DAG.getNode(ISD::ADD, dl, VT, Op, 6924 DAG.getNode(ISD::SRL, dl, VT, Op, 6925 DAG.getConstant(4, dl, ShVT))), 6926 Mask0F); 6927 // v = (v * 0x01010101...) >> (Len - 8) 6928 if (Len > 8) 6929 Op = 6930 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 6931 DAG.getConstant(Len - 8, dl, ShVT)); 6932 6933 Result = Op; 6934 return true; 6935 } 6936 6937 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 6938 SelectionDAG &DAG) const { 6939 SDLoc dl(Node); 6940 EVT VT = Node->getValueType(0); 6941 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6942 SDValue Op = Node->getOperand(0); 6943 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6944 6945 // If the non-ZERO_UNDEF version is supported we can use that instead. 6946 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 6947 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 6948 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 6949 return true; 6950 } 6951 6952 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6953 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 6954 EVT SetCCVT = 6955 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6956 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 6957 SDValue Zero = DAG.getConstant(0, dl, VT); 6958 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6959 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6960 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 6961 return true; 6962 } 6963 6964 // Only expand vector types if we have the appropriate vector bit operations. 6965 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6966 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 6967 !isOperationLegalOrCustom(ISD::SRL, VT) || 6968 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6969 return false; 6970 6971 // for now, we do this: 6972 // x = x | (x >> 1); 6973 // x = x | (x >> 2); 6974 // ... 6975 // x = x | (x >>16); 6976 // x = x | (x >>32); // for 64-bit input 6977 // return popcount(~x); 6978 // 6979 // Ref: "Hacker's Delight" by Henry Warren 6980 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 6981 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 6982 Op = DAG.getNode(ISD::OR, dl, VT, Op, 6983 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 6984 } 6985 Op = DAG.getNOT(dl, Op, VT); 6986 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 6987 return true; 6988 } 6989 6990 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 6991 SelectionDAG &DAG) const { 6992 SDLoc dl(Node); 6993 EVT VT = Node->getValueType(0); 6994 SDValue Op = Node->getOperand(0); 6995 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6996 6997 // If the non-ZERO_UNDEF version is supported we can use that instead. 6998 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 6999 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 7000 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 7001 return true; 7002 } 7003 7004 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7005 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7006 EVT SetCCVT = 7007 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7008 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7009 SDValue Zero = DAG.getConstant(0, dl, VT); 7010 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7011 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 7012 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7013 return true; 7014 } 7015 7016 // Only expand vector types if we have the appropriate vector bit operations. 7017 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7018 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7019 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 7020 !isOperationLegalOrCustom(ISD::SUB, VT) || 7021 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7022 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7023 return false; 7024 7025 // for now, we use: { return popcount(~x & (x - 1)); } 7026 // unless the target has ctlz but not ctpop, in which case we use: 7027 // { return 32 - nlz(~x & (x-1)); } 7028 // Ref: "Hacker's Delight" by Henry Warren 7029 SDValue Tmp = DAG.getNode( 7030 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7031 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7032 7033 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7034 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7035 Result = 7036 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7037 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7038 return true; 7039 } 7040 7041 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7042 return true; 7043 } 7044 7045 bool TargetLowering::expandABS(SDNode *N, SDValue &Result, 7046 SelectionDAG &DAG, bool IsNegative) const { 7047 SDLoc dl(N); 7048 EVT VT = N->getValueType(0); 7049 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7050 SDValue Op = N->getOperand(0); 7051 7052 // abs(x) -> smax(x,sub(0,x)) 7053 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7054 isOperationLegal(ISD::SMAX, VT)) { 7055 SDValue Zero = DAG.getConstant(0, dl, VT); 7056 Result = DAG.getNode(ISD::SMAX, dl, VT, Op, 7057 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7058 return true; 7059 } 7060 7061 // abs(x) -> umin(x,sub(0,x)) 7062 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7063 isOperationLegal(ISD::UMIN, VT)) { 7064 SDValue Zero = DAG.getConstant(0, dl, VT); 7065 Result = DAG.getNode(ISD::UMIN, dl, VT, Op, 7066 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7067 return true; 7068 } 7069 7070 // 0 - abs(x) -> smin(x, sub(0,x)) 7071 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7072 isOperationLegal(ISD::SMIN, VT)) { 7073 SDValue Zero = DAG.getConstant(0, dl, VT); 7074 Result = DAG.getNode(ISD::SMIN, dl, VT, Op, 7075 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7076 return true; 7077 } 7078 7079 // Only expand vector types if we have the appropriate vector operations. 7080 if (VT.isVector() && 7081 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7082 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7083 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7084 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7085 return false; 7086 7087 SDValue Shift = 7088 DAG.getNode(ISD::SRA, dl, VT, Op, 7089 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7090 if (!IsNegative) { 7091 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift); 7092 Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift); 7093 } else { 7094 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7095 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7096 Result = DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7097 } 7098 return true; 7099 } 7100 7101 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7102 SDLoc dl(N); 7103 EVT VT = N->getValueType(0); 7104 SDValue Op = N->getOperand(0); 7105 7106 if (!VT.isSimple()) 7107 return SDValue(); 7108 7109 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7110 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7111 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7112 default: 7113 return SDValue(); 7114 case MVT::i16: 7115 // Use a rotate by 8. This can be further expanded if necessary. 7116 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7117 case MVT::i32: 7118 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7119 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7120 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7121 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7122 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7123 DAG.getConstant(0xFF0000, dl, VT)); 7124 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7125 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7126 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7127 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7128 case MVT::i64: 7129 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7130 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7131 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7132 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7133 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7134 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7135 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7136 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7137 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7138 DAG.getConstant(255ULL<<48, dl, VT)); 7139 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7140 DAG.getConstant(255ULL<<40, dl, VT)); 7141 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7142 DAG.getConstant(255ULL<<32, dl, VT)); 7143 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7144 DAG.getConstant(255ULL<<24, dl, VT)); 7145 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7146 DAG.getConstant(255ULL<<16, dl, VT)); 7147 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7148 DAG.getConstant(255ULL<<8 , dl, VT)); 7149 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7150 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7151 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7152 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7153 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7154 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7155 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7156 } 7157 } 7158 7159 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 7160 SDLoc dl(N); 7161 EVT VT = N->getValueType(0); 7162 SDValue Op = N->getOperand(0); 7163 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7164 unsigned Sz = VT.getScalarSizeInBits(); 7165 7166 SDValue Tmp, Tmp2, Tmp3; 7167 7168 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 7169 // and finally the i1 pairs. 7170 // TODO: We can easily support i4/i2 legal types if any target ever does. 7171 if (Sz >= 8 && isPowerOf2_32(Sz)) { 7172 // Create the masks - repeating the pattern every byte. 7173 APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0)); 7174 APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC)); 7175 APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA)); 7176 APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 7177 APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33)); 7178 APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55)); 7179 7180 // BSWAP if the type is wider than a single byte. 7181 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 7182 7183 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4) 7184 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT)); 7185 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT)); 7186 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT)); 7187 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 7188 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7189 7190 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2) 7191 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT)); 7192 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT)); 7193 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT)); 7194 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 7195 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7196 7197 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1) 7198 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT)); 7199 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT)); 7200 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT)); 7201 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 7202 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7203 return Tmp; 7204 } 7205 7206 Tmp = DAG.getConstant(0, dl, VT); 7207 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 7208 if (I < J) 7209 Tmp2 = 7210 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 7211 else 7212 Tmp2 = 7213 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 7214 7215 APInt Shift(Sz, 1); 7216 Shift <<= J; 7217 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 7218 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 7219 } 7220 7221 return Tmp; 7222 } 7223 7224 std::pair<SDValue, SDValue> 7225 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 7226 SelectionDAG &DAG) const { 7227 SDLoc SL(LD); 7228 SDValue Chain = LD->getChain(); 7229 SDValue BasePTR = LD->getBasePtr(); 7230 EVT SrcVT = LD->getMemoryVT(); 7231 EVT DstVT = LD->getValueType(0); 7232 ISD::LoadExtType ExtType = LD->getExtensionType(); 7233 7234 if (SrcVT.isScalableVector()) 7235 report_fatal_error("Cannot scalarize scalable vector loads"); 7236 7237 unsigned NumElem = SrcVT.getVectorNumElements(); 7238 7239 EVT SrcEltVT = SrcVT.getScalarType(); 7240 EVT DstEltVT = DstVT.getScalarType(); 7241 7242 // A vector must always be stored in memory as-is, i.e. without any padding 7243 // between the elements, since various code depend on it, e.g. in the 7244 // handling of a bitcast of a vector type to int, which may be done with a 7245 // vector store followed by an integer load. A vector that does not have 7246 // elements that are byte-sized must therefore be stored as an integer 7247 // built out of the extracted vector elements. 7248 if (!SrcEltVT.isByteSized()) { 7249 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 7250 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 7251 7252 unsigned NumSrcBits = SrcVT.getSizeInBits(); 7253 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 7254 7255 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 7256 SDValue SrcEltBitMask = DAG.getConstant( 7257 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 7258 7259 // Load the whole vector and avoid masking off the top bits as it makes 7260 // the codegen worse. 7261 SDValue Load = 7262 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 7263 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 7264 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7265 7266 SmallVector<SDValue, 8> Vals; 7267 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7268 unsigned ShiftIntoIdx = 7269 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7270 SDValue ShiftAmount = 7271 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 7272 LoadVT, SL, /*LegalTypes=*/false); 7273 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 7274 SDValue Elt = 7275 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 7276 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 7277 7278 if (ExtType != ISD::NON_EXTLOAD) { 7279 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 7280 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 7281 } 7282 7283 Vals.push_back(Scalar); 7284 } 7285 7286 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7287 return std::make_pair(Value, Load.getValue(1)); 7288 } 7289 7290 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 7291 assert(SrcEltVT.isByteSized()); 7292 7293 SmallVector<SDValue, 8> Vals; 7294 SmallVector<SDValue, 8> LoadChains; 7295 7296 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7297 SDValue ScalarLoad = 7298 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 7299 LD->getPointerInfo().getWithOffset(Idx * Stride), 7300 SrcEltVT, LD->getOriginalAlign(), 7301 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7302 7303 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 7304 7305 Vals.push_back(ScalarLoad.getValue(0)); 7306 LoadChains.push_back(ScalarLoad.getValue(1)); 7307 } 7308 7309 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 7310 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7311 7312 return std::make_pair(Value, NewChain); 7313 } 7314 7315 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 7316 SelectionDAG &DAG) const { 7317 SDLoc SL(ST); 7318 7319 SDValue Chain = ST->getChain(); 7320 SDValue BasePtr = ST->getBasePtr(); 7321 SDValue Value = ST->getValue(); 7322 EVT StVT = ST->getMemoryVT(); 7323 7324 if (StVT.isScalableVector()) 7325 report_fatal_error("Cannot scalarize scalable vector stores"); 7326 7327 // The type of the data we want to save 7328 EVT RegVT = Value.getValueType(); 7329 EVT RegSclVT = RegVT.getScalarType(); 7330 7331 // The type of data as saved in memory. 7332 EVT MemSclVT = StVT.getScalarType(); 7333 7334 unsigned NumElem = StVT.getVectorNumElements(); 7335 7336 // A vector must always be stored in memory as-is, i.e. without any padding 7337 // between the elements, since various code depend on it, e.g. in the 7338 // handling of a bitcast of a vector type to int, which may be done with a 7339 // vector store followed by an integer load. A vector that does not have 7340 // elements that are byte-sized must therefore be stored as an integer 7341 // built out of the extracted vector elements. 7342 if (!MemSclVT.isByteSized()) { 7343 unsigned NumBits = StVT.getSizeInBits(); 7344 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 7345 7346 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 7347 7348 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7349 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7350 DAG.getVectorIdxConstant(Idx, SL)); 7351 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 7352 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 7353 unsigned ShiftIntoIdx = 7354 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7355 SDValue ShiftAmount = 7356 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 7357 SDValue ShiftedElt = 7358 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 7359 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 7360 } 7361 7362 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 7363 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7364 ST->getAAInfo()); 7365 } 7366 7367 // Store Stride in bytes 7368 unsigned Stride = MemSclVT.getSizeInBits() / 8; 7369 assert(Stride && "Zero stride!"); 7370 // Extract each of the elements from the original vector and save them into 7371 // memory individually. 7372 SmallVector<SDValue, 8> Stores; 7373 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7374 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7375 DAG.getVectorIdxConstant(Idx, SL)); 7376 7377 SDValue Ptr = 7378 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 7379 7380 // This scalar TruncStore may be illegal, but we legalize it later. 7381 SDValue Store = DAG.getTruncStore( 7382 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 7383 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7384 ST->getAAInfo()); 7385 7386 Stores.push_back(Store); 7387 } 7388 7389 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 7390 } 7391 7392 std::pair<SDValue, SDValue> 7393 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 7394 assert(LD->getAddressingMode() == ISD::UNINDEXED && 7395 "unaligned indexed loads not implemented!"); 7396 SDValue Chain = LD->getChain(); 7397 SDValue Ptr = LD->getBasePtr(); 7398 EVT VT = LD->getValueType(0); 7399 EVT LoadedVT = LD->getMemoryVT(); 7400 SDLoc dl(LD); 7401 auto &MF = DAG.getMachineFunction(); 7402 7403 if (VT.isFloatingPoint() || VT.isVector()) { 7404 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 7405 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 7406 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 7407 LoadedVT.isVector()) { 7408 // Scalarize the load and let the individual components be handled. 7409 return scalarizeVectorLoad(LD, DAG); 7410 } 7411 7412 // Expand to a (misaligned) integer load of the same size, 7413 // then bitconvert to floating point or vector. 7414 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 7415 LD->getMemOperand()); 7416 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 7417 if (LoadedVT != VT) 7418 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 7419 ISD::ANY_EXTEND, dl, VT, Result); 7420 7421 return std::make_pair(Result, newLoad.getValue(1)); 7422 } 7423 7424 // Copy the value to a (aligned) stack slot using (unaligned) integer 7425 // loads and stores, then do a (aligned) load from the stack slot. 7426 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 7427 unsigned LoadedBytes = LoadedVT.getStoreSize(); 7428 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7429 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 7430 7431 // Make sure the stack slot is also aligned for the register type. 7432 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 7433 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 7434 SmallVector<SDValue, 8> Stores; 7435 SDValue StackPtr = StackBase; 7436 unsigned Offset = 0; 7437 7438 EVT PtrVT = Ptr.getValueType(); 7439 EVT StackPtrVT = StackPtr.getValueType(); 7440 7441 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7442 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7443 7444 // Do all but one copies using the full register width. 7445 for (unsigned i = 1; i < NumRegs; i++) { 7446 // Load one integer register's worth from the original location. 7447 SDValue Load = DAG.getLoad( 7448 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 7449 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7450 LD->getAAInfo()); 7451 // Follow the load with a store to the stack slot. Remember the store. 7452 Stores.push_back(DAG.getStore( 7453 Load.getValue(1), dl, Load, StackPtr, 7454 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 7455 // Increment the pointers. 7456 Offset += RegBytes; 7457 7458 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7459 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7460 } 7461 7462 // The last copy may be partial. Do an extending load. 7463 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 7464 8 * (LoadedBytes - Offset)); 7465 SDValue Load = 7466 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 7467 LD->getPointerInfo().getWithOffset(Offset), MemVT, 7468 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7469 LD->getAAInfo()); 7470 // Follow the load with a store to the stack slot. Remember the store. 7471 // On big-endian machines this requires a truncating store to ensure 7472 // that the bits end up in the right place. 7473 Stores.push_back(DAG.getTruncStore( 7474 Load.getValue(1), dl, Load, StackPtr, 7475 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 7476 7477 // The order of the stores doesn't matter - say it with a TokenFactor. 7478 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7479 7480 // Finally, perform the original load only redirected to the stack slot. 7481 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 7482 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 7483 LoadedVT); 7484 7485 // Callers expect a MERGE_VALUES node. 7486 return std::make_pair(Load, TF); 7487 } 7488 7489 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 7490 "Unaligned load of unsupported type."); 7491 7492 // Compute the new VT that is half the size of the old one. This is an 7493 // integer MVT. 7494 unsigned NumBits = LoadedVT.getSizeInBits(); 7495 EVT NewLoadedVT; 7496 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 7497 NumBits >>= 1; 7498 7499 Align Alignment = LD->getOriginalAlign(); 7500 unsigned IncrementSize = NumBits / 8; 7501 ISD::LoadExtType HiExtType = LD->getExtensionType(); 7502 7503 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 7504 if (HiExtType == ISD::NON_EXTLOAD) 7505 HiExtType = ISD::ZEXTLOAD; 7506 7507 // Load the value in two parts 7508 SDValue Lo, Hi; 7509 if (DAG.getDataLayout().isLittleEndian()) { 7510 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7511 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7512 LD->getAAInfo()); 7513 7514 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7515 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 7516 LD->getPointerInfo().getWithOffset(IncrementSize), 7517 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7518 LD->getAAInfo()); 7519 } else { 7520 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7521 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7522 LD->getAAInfo()); 7523 7524 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7525 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 7526 LD->getPointerInfo().getWithOffset(IncrementSize), 7527 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7528 LD->getAAInfo()); 7529 } 7530 7531 // aggregate the two parts 7532 SDValue ShiftAmount = 7533 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 7534 DAG.getDataLayout())); 7535 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 7536 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 7537 7538 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 7539 Hi.getValue(1)); 7540 7541 return std::make_pair(Result, TF); 7542 } 7543 7544 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 7545 SelectionDAG &DAG) const { 7546 assert(ST->getAddressingMode() == ISD::UNINDEXED && 7547 "unaligned indexed stores not implemented!"); 7548 SDValue Chain = ST->getChain(); 7549 SDValue Ptr = ST->getBasePtr(); 7550 SDValue Val = ST->getValue(); 7551 EVT VT = Val.getValueType(); 7552 Align Alignment = ST->getOriginalAlign(); 7553 auto &MF = DAG.getMachineFunction(); 7554 EVT StoreMemVT = ST->getMemoryVT(); 7555 7556 SDLoc dl(ST); 7557 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 7558 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7559 if (isTypeLegal(intVT)) { 7560 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 7561 StoreMemVT.isVector()) { 7562 // Scalarize the store and let the individual components be handled. 7563 SDValue Result = scalarizeVectorStore(ST, DAG); 7564 return Result; 7565 } 7566 // Expand to a bitconvert of the value to the integer type of the 7567 // same size, then a (misaligned) int store. 7568 // FIXME: Does not handle truncating floating point stores! 7569 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 7570 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 7571 Alignment, ST->getMemOperand()->getFlags()); 7572 return Result; 7573 } 7574 // Do a (aligned) store to a stack slot, then copy from the stack slot 7575 // to the final destination using (unaligned) integer loads and stores. 7576 MVT RegVT = getRegisterType( 7577 *DAG.getContext(), 7578 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 7579 EVT PtrVT = Ptr.getValueType(); 7580 unsigned StoredBytes = StoreMemVT.getStoreSize(); 7581 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7582 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 7583 7584 // Make sure the stack slot is also aligned for the register type. 7585 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 7586 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 7587 7588 // Perform the original store, only redirected to the stack slot. 7589 SDValue Store = DAG.getTruncStore( 7590 Chain, dl, Val, StackPtr, 7591 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 7592 7593 EVT StackPtrVT = StackPtr.getValueType(); 7594 7595 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7596 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7597 SmallVector<SDValue, 8> Stores; 7598 unsigned Offset = 0; 7599 7600 // Do all but one copies using the full register width. 7601 for (unsigned i = 1; i < NumRegs; i++) { 7602 // Load one integer register's worth from the stack slot. 7603 SDValue Load = DAG.getLoad( 7604 RegVT, dl, Store, StackPtr, 7605 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 7606 // Store it to the final location. Remember the store. 7607 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 7608 ST->getPointerInfo().getWithOffset(Offset), 7609 ST->getOriginalAlign(), 7610 ST->getMemOperand()->getFlags())); 7611 // Increment the pointers. 7612 Offset += RegBytes; 7613 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7614 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7615 } 7616 7617 // The last store may be partial. Do a truncating store. On big-endian 7618 // machines this requires an extending load from the stack slot to ensure 7619 // that the bits are in the right place. 7620 EVT LoadMemVT = 7621 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 7622 7623 // Load from the stack slot. 7624 SDValue Load = DAG.getExtLoad( 7625 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 7626 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 7627 7628 Stores.push_back( 7629 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 7630 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 7631 ST->getOriginalAlign(), 7632 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 7633 // The order of the stores doesn't matter - say it with a TokenFactor. 7634 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7635 return Result; 7636 } 7637 7638 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 7639 "Unaligned store of unknown type."); 7640 // Get the half-size VT 7641 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 7642 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 7643 unsigned IncrementSize = NumBits / 8; 7644 7645 // Divide the stored value in two parts. 7646 SDValue ShiftAmount = DAG.getConstant( 7647 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 7648 SDValue Lo = Val; 7649 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 7650 7651 // Store the two parts 7652 SDValue Store1, Store2; 7653 Store1 = DAG.getTruncStore(Chain, dl, 7654 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 7655 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 7656 ST->getMemOperand()->getFlags()); 7657 7658 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7659 Store2 = DAG.getTruncStore( 7660 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 7661 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 7662 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 7663 7664 SDValue Result = 7665 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 7666 return Result; 7667 } 7668 7669 SDValue 7670 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 7671 const SDLoc &DL, EVT DataVT, 7672 SelectionDAG &DAG, 7673 bool IsCompressedMemory) const { 7674 SDValue Increment; 7675 EVT AddrVT = Addr.getValueType(); 7676 EVT MaskVT = Mask.getValueType(); 7677 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 7678 "Incompatible types of Data and Mask"); 7679 if (IsCompressedMemory) { 7680 if (DataVT.isScalableVector()) 7681 report_fatal_error( 7682 "Cannot currently handle compressed memory with scalable vectors"); 7683 // Incrementing the pointer according to number of '1's in the mask. 7684 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 7685 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 7686 if (MaskIntVT.getSizeInBits() < 32) { 7687 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 7688 MaskIntVT = MVT::i32; 7689 } 7690 7691 // Count '1's with POPCNT. 7692 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 7693 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 7694 // Scale is an element size in bytes. 7695 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 7696 AddrVT); 7697 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 7698 } else if (DataVT.isScalableVector()) { 7699 Increment = DAG.getVScale(DL, AddrVT, 7700 APInt(AddrVT.getFixedSizeInBits(), 7701 DataVT.getStoreSize().getKnownMinSize())); 7702 } else 7703 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 7704 7705 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 7706 } 7707 7708 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 7709 SDValue Idx, 7710 EVT VecVT, 7711 const SDLoc &dl) { 7712 if (!VecVT.isScalableVector() && isa<ConstantSDNode>(Idx)) 7713 return Idx; 7714 7715 EVT IdxVT = Idx.getValueType(); 7716 unsigned NElts = VecVT.getVectorMinNumElements(); 7717 if (VecVT.isScalableVector()) { 7718 // If this is a constant index and we know the value is less than the 7719 // minimum number of elements then it's safe to return Idx. 7720 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 7721 if (IdxCst->getZExtValue() < NElts) 7722 return Idx; 7723 SDValue VS = 7724 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 7725 SDValue Sub = 7726 DAG.getNode(ISD::SUB, dl, IdxVT, VS, DAG.getConstant(1, dl, IdxVT)); 7727 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 7728 } 7729 if (isPowerOf2_32(NElts)) { 7730 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 7731 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 7732 DAG.getConstant(Imm, dl, IdxVT)); 7733 } 7734 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 7735 DAG.getConstant(NElts - 1, dl, IdxVT)); 7736 } 7737 7738 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 7739 SDValue VecPtr, EVT VecVT, 7740 SDValue Index) const { 7741 SDLoc dl(Index); 7742 // Make sure the index type is big enough to compute in. 7743 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 7744 7745 EVT EltVT = VecVT.getVectorElementType(); 7746 7747 // Calculate the element offset and add it to the pointer. 7748 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 7749 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 7750 "Converting bits to bytes lost precision"); 7751 7752 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 7753 7754 EVT IdxVT = Index.getValueType(); 7755 7756 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 7757 DAG.getConstant(EltSize, dl, IdxVT)); 7758 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 7759 } 7760 7761 //===----------------------------------------------------------------------===// 7762 // Implementation of Emulated TLS Model 7763 //===----------------------------------------------------------------------===// 7764 7765 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 7766 SelectionDAG &DAG) const { 7767 // Access to address of TLS varialbe xyz is lowered to a function call: 7768 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 7769 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7770 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 7771 SDLoc dl(GA); 7772 7773 ArgListTy Args; 7774 ArgListEntry Entry; 7775 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 7776 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 7777 StringRef EmuTlsVarName(NameString); 7778 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 7779 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 7780 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 7781 Entry.Ty = VoidPtrType; 7782 Args.push_back(Entry); 7783 7784 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 7785 7786 TargetLowering::CallLoweringInfo CLI(DAG); 7787 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 7788 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 7789 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7790 7791 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7792 // At last for X86 targets, maybe good for other targets too? 7793 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7794 MFI.setAdjustsStack(true); // Is this only for X86 target? 7795 MFI.setHasCalls(true); 7796 7797 assert((GA->getOffset() == 0) && 7798 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 7799 return CallResult.first; 7800 } 7801 7802 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 7803 SelectionDAG &DAG) const { 7804 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 7805 if (!isCtlzFast()) 7806 return SDValue(); 7807 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7808 SDLoc dl(Op); 7809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7810 if (C->isNullValue() && CC == ISD::SETEQ) { 7811 EVT VT = Op.getOperand(0).getValueType(); 7812 SDValue Zext = Op.getOperand(0); 7813 if (VT.bitsLT(MVT::i32)) { 7814 VT = MVT::i32; 7815 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 7816 } 7817 unsigned Log2b = Log2_32(VT.getSizeInBits()); 7818 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 7819 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 7820 DAG.getConstant(Log2b, dl, MVT::i32)); 7821 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 7822 } 7823 } 7824 return SDValue(); 7825 } 7826 7827 // Convert redundant addressing modes (e.g. scaling is redundant 7828 // when accessing bytes). 7829 ISD::MemIndexType 7830 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT, 7831 SDValue Offsets) const { 7832 bool IsScaledIndex = 7833 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED); 7834 bool IsSignedIndex = 7835 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED); 7836 7837 // Scaling is unimportant for bytes, canonicalize to unscaled. 7838 if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) { 7839 IsScaledIndex = false; 7840 IndexType = IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED; 7841 } 7842 7843 return IndexType; 7844 } 7845 7846 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 7847 SDValue Op0 = Node->getOperand(0); 7848 SDValue Op1 = Node->getOperand(1); 7849 EVT VT = Op0.getValueType(); 7850 unsigned Opcode = Node->getOpcode(); 7851 SDLoc DL(Node); 7852 7853 // umin(x,y) -> sub(x,usubsat(x,y)) 7854 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 7855 isOperationLegal(ISD::USUBSAT, VT)) { 7856 return DAG.getNode(ISD::SUB, DL, VT, Op0, 7857 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 7858 } 7859 7860 // umax(x,y) -> add(x,usubsat(y,x)) 7861 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 7862 isOperationLegal(ISD::USUBSAT, VT)) { 7863 return DAG.getNode(ISD::ADD, DL, VT, Op0, 7864 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 7865 } 7866 7867 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 7868 ISD::CondCode CC; 7869 switch (Opcode) { 7870 default: llvm_unreachable("How did we get here?"); 7871 case ISD::SMAX: CC = ISD::SETGT; break; 7872 case ISD::SMIN: CC = ISD::SETLT; break; 7873 case ISD::UMAX: CC = ISD::SETUGT; break; 7874 case ISD::UMIN: CC = ISD::SETULT; break; 7875 } 7876 7877 // FIXME: Should really try to split the vector in case it's legal on a 7878 // subvector. 7879 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7880 return DAG.UnrollVectorOp(Node); 7881 7882 SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC); 7883 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 7884 } 7885 7886 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 7887 unsigned Opcode = Node->getOpcode(); 7888 SDValue LHS = Node->getOperand(0); 7889 SDValue RHS = Node->getOperand(1); 7890 EVT VT = LHS.getValueType(); 7891 SDLoc dl(Node); 7892 7893 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7894 assert(VT.isInteger() && "Expected operands to be integers"); 7895 7896 // usub.sat(a, b) -> umax(a, b) - b 7897 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 7898 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 7899 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 7900 } 7901 7902 // uadd.sat(a, b) -> umin(a, ~b) + b 7903 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 7904 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 7905 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 7906 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 7907 } 7908 7909 unsigned OverflowOp; 7910 switch (Opcode) { 7911 case ISD::SADDSAT: 7912 OverflowOp = ISD::SADDO; 7913 break; 7914 case ISD::UADDSAT: 7915 OverflowOp = ISD::UADDO; 7916 break; 7917 case ISD::SSUBSAT: 7918 OverflowOp = ISD::SSUBO; 7919 break; 7920 case ISD::USUBSAT: 7921 OverflowOp = ISD::USUBO; 7922 break; 7923 default: 7924 llvm_unreachable("Expected method to receive signed or unsigned saturation " 7925 "addition or subtraction node."); 7926 } 7927 7928 // FIXME: Should really try to split the vector in case it's legal on a 7929 // subvector. 7930 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7931 return DAG.UnrollVectorOp(Node); 7932 7933 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 7934 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7935 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7936 SDValue SumDiff = Result.getValue(0); 7937 SDValue Overflow = Result.getValue(1); 7938 SDValue Zero = DAG.getConstant(0, dl, VT); 7939 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 7940 7941 if (Opcode == ISD::UADDSAT) { 7942 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7943 // (LHS + RHS) | OverflowMask 7944 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7945 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 7946 } 7947 // Overflow ? 0xffff.... : (LHS + RHS) 7948 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 7949 } 7950 7951 if (Opcode == ISD::USUBSAT) { 7952 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7953 // (LHS - RHS) & ~OverflowMask 7954 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7955 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 7956 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 7957 } 7958 // Overflow ? 0 : (LHS - RHS) 7959 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 7960 } 7961 7962 // SatMax -> Overflow && SumDiff < 0 7963 // SatMin -> Overflow && SumDiff >= 0 7964 APInt MinVal = APInt::getSignedMinValue(BitWidth); 7965 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 7966 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7967 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7968 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 7969 Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin); 7970 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 7971 } 7972 7973 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 7974 unsigned Opcode = Node->getOpcode(); 7975 bool IsSigned = Opcode == ISD::SSHLSAT; 7976 SDValue LHS = Node->getOperand(0); 7977 SDValue RHS = Node->getOperand(1); 7978 EVT VT = LHS.getValueType(); 7979 SDLoc dl(Node); 7980 7981 assert((Node->getOpcode() == ISD::SSHLSAT || 7982 Node->getOpcode() == ISD::USHLSAT) && 7983 "Expected a SHLSAT opcode"); 7984 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7985 assert(VT.isInteger() && "Expected operands to be integers"); 7986 7987 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 7988 7989 unsigned BW = VT.getScalarSizeInBits(); 7990 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 7991 SDValue Orig = 7992 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 7993 7994 SDValue SatVal; 7995 if (IsSigned) { 7996 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 7997 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 7998 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 7999 SatMin, SatMax, ISD::SETLT); 8000 } else { 8001 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8002 } 8003 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8004 8005 return Result; 8006 } 8007 8008 SDValue 8009 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8010 assert((Node->getOpcode() == ISD::SMULFIX || 8011 Node->getOpcode() == ISD::UMULFIX || 8012 Node->getOpcode() == ISD::SMULFIXSAT || 8013 Node->getOpcode() == ISD::UMULFIXSAT) && 8014 "Expected a fixed point multiplication opcode"); 8015 8016 SDLoc dl(Node); 8017 SDValue LHS = Node->getOperand(0); 8018 SDValue RHS = Node->getOperand(1); 8019 EVT VT = LHS.getValueType(); 8020 unsigned Scale = Node->getConstantOperandVal(2); 8021 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8022 Node->getOpcode() == ISD::UMULFIXSAT); 8023 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8024 Node->getOpcode() == ISD::SMULFIXSAT); 8025 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8026 unsigned VTSize = VT.getScalarSizeInBits(); 8027 8028 if (!Scale) { 8029 // [us]mul.fix(a, b, 0) -> mul(a, b) 8030 if (!Saturating) { 8031 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8032 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8033 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8034 SDValue Result = 8035 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8036 SDValue Product = Result.getValue(0); 8037 SDValue Overflow = Result.getValue(1); 8038 SDValue Zero = DAG.getConstant(0, dl, VT); 8039 8040 APInt MinVal = APInt::getSignedMinValue(VTSize); 8041 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8042 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8043 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8044 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT); 8045 Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin); 8046 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8047 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8048 SDValue Result = 8049 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8050 SDValue Product = Result.getValue(0); 8051 SDValue Overflow = Result.getValue(1); 8052 8053 APInt MaxVal = APInt::getMaxValue(VTSize); 8054 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8055 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8056 } 8057 } 8058 8059 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8060 "Expected scale to be less than the number of bits if signed or at " 8061 "most the number of bits if unsigned."); 8062 assert(LHS.getValueType() == RHS.getValueType() && 8063 "Expected both operands to be the same type"); 8064 8065 // Get the upper and lower bits of the result. 8066 SDValue Lo, Hi; 8067 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8068 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8069 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8070 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8071 Lo = Result.getValue(0); 8072 Hi = Result.getValue(1); 8073 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8074 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8075 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8076 } else if (VT.isVector()) { 8077 return SDValue(); 8078 } else { 8079 report_fatal_error("Unable to expand fixed point multiplication."); 8080 } 8081 8082 if (Scale == VTSize) 8083 // Result is just the top half since we'd be shifting by the width of the 8084 // operand. Overflow impossible so this works for both UMULFIX and 8085 // UMULFIXSAT. 8086 return Hi; 8087 8088 // The result will need to be shifted right by the scale since both operands 8089 // are scaled. The result is given to us in 2 halves, so we only want part of 8090 // both in the result. 8091 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8092 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8093 DAG.getConstant(Scale, dl, ShiftTy)); 8094 if (!Saturating) 8095 return Result; 8096 8097 if (!Signed) { 8098 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8099 // widened multiplication) aren't all zeroes. 8100 8101 // Saturate to max if ((Hi >> Scale) != 0), 8102 // which is the same as if (Hi > ((1 << Scale) - 1)) 8103 APInt MaxVal = APInt::getMaxValue(VTSize); 8104 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8105 dl, VT); 8106 Result = DAG.getSelectCC(dl, Hi, LowMask, 8107 DAG.getConstant(MaxVal, dl, VT), Result, 8108 ISD::SETUGT); 8109 8110 return Result; 8111 } 8112 8113 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8114 // widened multiplication) aren't all ones or all zeroes. 8115 8116 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8117 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8118 8119 if (Scale == 0) { 8120 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8121 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8122 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8123 // Saturated to SatMin if wide product is negative, and SatMax if wide 8124 // product is positive ... 8125 SDValue Zero = DAG.getConstant(0, dl, VT); 8126 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8127 ISD::SETLT); 8128 // ... but only if we overflowed. 8129 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 8130 } 8131 8132 // We handled Scale==0 above so all the bits to examine is in Hi. 8133 8134 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 8135 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 8136 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 8137 dl, VT); 8138 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 8139 // Saturate to min if (Hi >> (Scale - 1)) < -1), 8140 // which is the same as if (HI < (-1 << (Scale - 1)) 8141 SDValue HighMask = 8142 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 8143 dl, VT); 8144 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 8145 return Result; 8146 } 8147 8148 SDValue 8149 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 8150 SDValue LHS, SDValue RHS, 8151 unsigned Scale, SelectionDAG &DAG) const { 8152 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 8153 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 8154 "Expected a fixed point division opcode"); 8155 8156 EVT VT = LHS.getValueType(); 8157 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 8158 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 8159 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8160 8161 // If there is enough room in the type to upscale the LHS or downscale the 8162 // RHS before the division, we can perform it in this type without having to 8163 // resize. For signed operations, the LHS headroom is the number of 8164 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8165 // The headroom for the RHS is the number of trailing zeroes. 8166 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8167 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8168 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 8169 8170 // For signed saturating operations, we need to be able to detect true integer 8171 // division overflow; that is, when you have MIN / -EPS. However, this 8172 // is undefined behavior and if we emit divisions that could take such 8173 // values it may cause undesired behavior (arithmetic exceptions on x86, for 8174 // example). 8175 // Avoid this by requiring an extra bit so that we never get this case. 8176 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 8177 // signed saturating division, we need to emit a whopping 32-bit division. 8178 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 8179 return SDValue(); 8180 8181 unsigned LHSShift = std::min(LHSLead, Scale); 8182 unsigned RHSShift = Scale - LHSShift; 8183 8184 // At this point, we know that if we shift the LHS up by LHSShift and the 8185 // RHS down by RHSShift, we can emit a regular division with a final scaling 8186 // factor of Scale. 8187 8188 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8189 if (LHSShift) 8190 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 8191 DAG.getConstant(LHSShift, dl, ShiftTy)); 8192 if (RHSShift) 8193 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 8194 DAG.getConstant(RHSShift, dl, ShiftTy)); 8195 8196 SDValue Quot; 8197 if (Signed) { 8198 // For signed operations, if the resulting quotient is negative and the 8199 // remainder is nonzero, subtract 1 from the quotient to round towards 8200 // negative infinity. 8201 SDValue Rem; 8202 // FIXME: Ideally we would always produce an SDIVREM here, but if the 8203 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 8204 // we couldn't just form a libcall, but the type legalizer doesn't do it. 8205 if (isTypeLegal(VT) && 8206 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 8207 Quot = DAG.getNode(ISD::SDIVREM, dl, 8208 DAG.getVTList(VT, VT), 8209 LHS, RHS); 8210 Rem = Quot.getValue(1); 8211 Quot = Quot.getValue(0); 8212 } else { 8213 Quot = DAG.getNode(ISD::SDIV, dl, VT, 8214 LHS, RHS); 8215 Rem = DAG.getNode(ISD::SREM, dl, VT, 8216 LHS, RHS); 8217 } 8218 SDValue Zero = DAG.getConstant(0, dl, VT); 8219 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 8220 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 8221 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 8222 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 8223 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 8224 DAG.getConstant(1, dl, VT)); 8225 Quot = DAG.getSelect(dl, VT, 8226 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 8227 Sub1, Quot); 8228 } else 8229 Quot = DAG.getNode(ISD::UDIV, dl, VT, 8230 LHS, RHS); 8231 8232 return Quot; 8233 } 8234 8235 void TargetLowering::expandUADDSUBO( 8236 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8237 SDLoc dl(Node); 8238 SDValue LHS = Node->getOperand(0); 8239 SDValue RHS = Node->getOperand(1); 8240 bool IsAdd = Node->getOpcode() == ISD::UADDO; 8241 8242 // If ADD/SUBCARRY is legal, use that instead. 8243 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 8244 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 8245 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 8246 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 8247 { LHS, RHS, CarryIn }); 8248 Result = SDValue(NodeCarry.getNode(), 0); 8249 Overflow = SDValue(NodeCarry.getNode(), 1); 8250 return; 8251 } 8252 8253 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8254 LHS.getValueType(), LHS, RHS); 8255 8256 EVT ResultType = Node->getValueType(1); 8257 EVT SetCCType = getSetCCResultType( 8258 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8259 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 8260 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 8261 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8262 } 8263 8264 void TargetLowering::expandSADDSUBO( 8265 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8266 SDLoc dl(Node); 8267 SDValue LHS = Node->getOperand(0); 8268 SDValue RHS = Node->getOperand(1); 8269 bool IsAdd = Node->getOpcode() == ISD::SADDO; 8270 8271 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8272 LHS.getValueType(), LHS, RHS); 8273 8274 EVT ResultType = Node->getValueType(1); 8275 EVT OType = getSetCCResultType( 8276 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8277 8278 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 8279 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 8280 if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) { 8281 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 8282 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 8283 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8284 return; 8285 } 8286 8287 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 8288 8289 // For an addition, the result should be less than one of the operands (LHS) 8290 // if and only if the other operand (RHS) is negative, otherwise there will 8291 // be overflow. 8292 // For a subtraction, the result should be less than one of the operands 8293 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 8294 // otherwise there will be overflow. 8295 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 8296 SDValue ConditionRHS = 8297 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 8298 8299 Overflow = DAG.getBoolExtOrTrunc( 8300 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 8301 ResultType, ResultType); 8302 } 8303 8304 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 8305 SDValue &Overflow, SelectionDAG &DAG) const { 8306 SDLoc dl(Node); 8307 EVT VT = Node->getValueType(0); 8308 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8309 SDValue LHS = Node->getOperand(0); 8310 SDValue RHS = Node->getOperand(1); 8311 bool isSigned = Node->getOpcode() == ISD::SMULO; 8312 8313 // For power-of-two multiplications we can use a simpler shift expansion. 8314 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 8315 const APInt &C = RHSC->getAPIntValue(); 8316 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 8317 if (C.isPowerOf2()) { 8318 // smulo(x, signed_min) is same as umulo(x, signed_min). 8319 bool UseArithShift = isSigned && !C.isMinSignedValue(); 8320 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8321 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 8322 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 8323 Overflow = DAG.getSetCC(dl, SetCCVT, 8324 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 8325 dl, VT, Result, ShiftAmt), 8326 LHS, ISD::SETNE); 8327 return true; 8328 } 8329 } 8330 8331 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 8332 if (VT.isVector()) 8333 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 8334 VT.getVectorNumElements()); 8335 8336 SDValue BottomHalf; 8337 SDValue TopHalf; 8338 static const unsigned Ops[2][3] = 8339 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 8340 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 8341 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 8342 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8343 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 8344 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 8345 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 8346 RHS); 8347 TopHalf = BottomHalf.getValue(1); 8348 } else if (isTypeLegal(WideVT)) { 8349 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 8350 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 8351 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 8352 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 8353 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 8354 getShiftAmountTy(WideVT, DAG.getDataLayout())); 8355 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 8356 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 8357 } else { 8358 if (VT.isVector()) 8359 return false; 8360 8361 // We can fall back to a libcall with an illegal type for the MUL if we 8362 // have a libcall big enough. 8363 // Also, we can fall back to a division in some cases, but that's a big 8364 // performance hit in the general case. 8365 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 8366 if (WideVT == MVT::i16) 8367 LC = RTLIB::MUL_I16; 8368 else if (WideVT == MVT::i32) 8369 LC = RTLIB::MUL_I32; 8370 else if (WideVT == MVT::i64) 8371 LC = RTLIB::MUL_I64; 8372 else if (WideVT == MVT::i128) 8373 LC = RTLIB::MUL_I128; 8374 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 8375 8376 SDValue HiLHS; 8377 SDValue HiRHS; 8378 if (isSigned) { 8379 // The high part is obtained by SRA'ing all but one of the bits of low 8380 // part. 8381 unsigned LoSize = VT.getFixedSizeInBits(); 8382 HiLHS = 8383 DAG.getNode(ISD::SRA, dl, VT, LHS, 8384 DAG.getConstant(LoSize - 1, dl, 8385 getPointerTy(DAG.getDataLayout()))); 8386 HiRHS = 8387 DAG.getNode(ISD::SRA, dl, VT, RHS, 8388 DAG.getConstant(LoSize - 1, dl, 8389 getPointerTy(DAG.getDataLayout()))); 8390 } else { 8391 HiLHS = DAG.getConstant(0, dl, VT); 8392 HiRHS = DAG.getConstant(0, dl, VT); 8393 } 8394 8395 // Here we're passing the 2 arguments explicitly as 4 arguments that are 8396 // pre-lowered to the correct types. This all depends upon WideVT not 8397 // being a legal type for the architecture and thus has to be split to 8398 // two arguments. 8399 SDValue Ret; 8400 TargetLowering::MakeLibCallOptions CallOptions; 8401 CallOptions.setSExt(isSigned); 8402 CallOptions.setIsPostTypeLegalization(true); 8403 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 8404 // Halves of WideVT are packed into registers in different order 8405 // depending on platform endianness. This is usually handled by 8406 // the C calling convention, but we can't defer to it in 8407 // the legalizer. 8408 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 8409 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8410 } else { 8411 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 8412 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8413 } 8414 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 8415 "Ret value is a collection of constituent nodes holding result."); 8416 if (DAG.getDataLayout().isLittleEndian()) { 8417 // Same as above. 8418 BottomHalf = Ret.getOperand(0); 8419 TopHalf = Ret.getOperand(1); 8420 } else { 8421 BottomHalf = Ret.getOperand(1); 8422 TopHalf = Ret.getOperand(0); 8423 } 8424 } 8425 8426 Result = BottomHalf; 8427 if (isSigned) { 8428 SDValue ShiftAmt = DAG.getConstant( 8429 VT.getScalarSizeInBits() - 1, dl, 8430 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 8431 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 8432 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 8433 } else { 8434 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 8435 DAG.getConstant(0, dl, VT), ISD::SETNE); 8436 } 8437 8438 // Truncate the result if SetCC returns a larger type than needed. 8439 EVT RType = Node->getValueType(1); 8440 if (RType.bitsLT(Overflow.getValueType())) 8441 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 8442 8443 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 8444 "Unexpected result type for S/UMULO legalization"); 8445 return true; 8446 } 8447 8448 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 8449 SDLoc dl(Node); 8450 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8451 SDValue Op = Node->getOperand(0); 8452 EVT VT = Op.getValueType(); 8453 8454 if (VT.isScalableVector()) 8455 report_fatal_error( 8456 "Expanding reductions for scalable vectors is undefined."); 8457 8458 // Try to use a shuffle reduction for power of two vectors. 8459 if (VT.isPow2VectorType()) { 8460 while (VT.getVectorNumElements() > 1) { 8461 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8462 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 8463 break; 8464 8465 SDValue Lo, Hi; 8466 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 8467 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 8468 VT = HalfVT; 8469 } 8470 } 8471 8472 EVT EltVT = VT.getVectorElementType(); 8473 unsigned NumElts = VT.getVectorNumElements(); 8474 8475 SmallVector<SDValue, 8> Ops; 8476 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 8477 8478 SDValue Res = Ops[0]; 8479 for (unsigned i = 1; i < NumElts; i++) 8480 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 8481 8482 // Result type may be wider than element type. 8483 if (EltVT != Node->getValueType(0)) 8484 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 8485 return Res; 8486 } 8487 8488 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 8489 SDLoc dl(Node); 8490 SDValue AccOp = Node->getOperand(0); 8491 SDValue VecOp = Node->getOperand(1); 8492 SDNodeFlags Flags = Node->getFlags(); 8493 8494 EVT VT = VecOp.getValueType(); 8495 EVT EltVT = VT.getVectorElementType(); 8496 8497 if (VT.isScalableVector()) 8498 report_fatal_error( 8499 "Expanding reductions for scalable vectors is undefined."); 8500 8501 unsigned NumElts = VT.getVectorNumElements(); 8502 8503 SmallVector<SDValue, 8> Ops; 8504 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 8505 8506 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8507 8508 SDValue Res = AccOp; 8509 for (unsigned i = 0; i < NumElts; i++) 8510 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 8511 8512 return Res; 8513 } 8514 8515 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 8516 SelectionDAG &DAG) const { 8517 EVT VT = Node->getValueType(0); 8518 SDLoc dl(Node); 8519 bool isSigned = Node->getOpcode() == ISD::SREM; 8520 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 8521 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 8522 SDValue Dividend = Node->getOperand(0); 8523 SDValue Divisor = Node->getOperand(1); 8524 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 8525 SDVTList VTs = DAG.getVTList(VT, VT); 8526 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 8527 return true; 8528 } 8529 if (isOperationLegalOrCustom(DivOpc, VT)) { 8530 // X % Y -> X-X/Y*Y 8531 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 8532 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 8533 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 8534 return true; 8535 } 8536 return false; 8537 } 8538 8539 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 8540 SelectionDAG &DAG) const { 8541 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 8542 SDLoc dl(SDValue(Node, 0)); 8543 SDValue Src = Node->getOperand(0); 8544 8545 // DstVT is the result type, while SatVT is the size to which we saturate 8546 EVT SrcVT = Src.getValueType(); 8547 EVT DstVT = Node->getValueType(0); 8548 8549 unsigned SatWidth = Node->getConstantOperandVal(1); 8550 unsigned DstWidth = DstVT.getScalarSizeInBits(); 8551 assert(SatWidth <= DstWidth && 8552 "Expected saturation width smaller than result width"); 8553 8554 // Determine minimum and maximum integer values and their corresponding 8555 // floating-point values. 8556 APInt MinInt, MaxInt; 8557 if (IsSigned) { 8558 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth); 8559 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth); 8560 } else { 8561 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth); 8562 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth); 8563 } 8564 8565 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 8566 // libcall emission cannot handle this. Large result types will fail. 8567 if (SrcVT == MVT::f16) { 8568 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 8569 SrcVT = Src.getValueType(); 8570 } 8571 8572 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8573 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8574 8575 APFloat::opStatus MinStatus = 8576 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 8577 APFloat::opStatus MaxStatus = 8578 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 8579 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 8580 !(MaxStatus & APFloat::opStatus::opInexact); 8581 8582 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 8583 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 8584 8585 // If the integer bounds are exactly representable as floats and min/max are 8586 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 8587 // of comparisons and selects. 8588 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 8589 isOperationLegal(ISD::FMAXNUM, SrcVT); 8590 if (AreExactFloatBounds && MinMaxLegal) { 8591 SDValue Clamped = Src; 8592 8593 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 8594 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 8595 // Clamp by MaxFloat from above. NaN cannot occur. 8596 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 8597 // Convert clamped value to integer. 8598 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 8599 dl, DstVT, Clamped); 8600 8601 // In the unsigned case we're done, because we mapped NaN to MinFloat, 8602 // which will cast to zero. 8603 if (!IsSigned) 8604 return FpToInt; 8605 8606 // Otherwise, select 0 if Src is NaN. 8607 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8608 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 8609 ISD::CondCode::SETUO); 8610 } 8611 8612 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 8613 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 8614 8615 // Result of direct conversion. The assumption here is that the operation is 8616 // non-trapping and it's fine to apply it to an out-of-range value if we 8617 // select it away later. 8618 SDValue FpToInt = 8619 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 8620 8621 SDValue Select = FpToInt; 8622 8623 // If Src ULT MinFloat, select MinInt. In particular, this also selects 8624 // MinInt if Src is NaN. 8625 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 8626 ISD::CondCode::SETULT); 8627 // If Src OGT MaxFloat, select MaxInt. 8628 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 8629 ISD::CondCode::SETOGT); 8630 8631 // In the unsigned case we are done, because we mapped NaN to MinInt, which 8632 // is already zero. 8633 if (!IsSigned) 8634 return Select; 8635 8636 // Otherwise, select 0 if Src is NaN. 8637 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8638 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 8639 } 8640 8641 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 8642 SelectionDAG &DAG) const { 8643 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 8644 assert(Node->getValueType(0).isScalableVector() && 8645 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 8646 8647 EVT VT = Node->getValueType(0); 8648 SDValue V1 = Node->getOperand(0); 8649 SDValue V2 = Node->getOperand(1); 8650 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 8651 SDLoc DL(Node); 8652 8653 // Expand through memory thusly: 8654 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 8655 // Store V1, Ptr 8656 // Store V2, Ptr + sizeof(V1) 8657 // If (Imm < 0) 8658 // TrailingElts = -Imm 8659 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 8660 // else 8661 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 8662 // Res = Load Ptr 8663 8664 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 8665 8666 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8667 VT.getVectorElementCount() * 2); 8668 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 8669 EVT PtrVT = StackPtr.getValueType(); 8670 auto &MF = DAG.getMachineFunction(); 8671 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8672 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 8673 8674 // Store the lo part of CONCAT_VECTORS(V1, V2) 8675 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 8676 // Store the hi part of CONCAT_VECTORS(V1, V2) 8677 SDValue OffsetToV2 = DAG.getVScale( 8678 DL, PtrVT, 8679 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 8680 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 8681 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 8682 8683 if (Imm >= 0) { 8684 // Load back the required element. getVectorElementPointer takes care of 8685 // clamping the index if it's out-of-bounds. 8686 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 8687 // Load the spliced result 8688 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 8689 MachinePointerInfo::getUnknownStack(MF)); 8690 } 8691 8692 uint64_t TrailingElts = -Imm; 8693 8694 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 8695 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 8696 SDValue TrailingBytes = 8697 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 8698 8699 if (TrailingElts > VT.getVectorMinNumElements()) { 8700 SDValue VLBytes = DAG.getVScale( 8701 DL, PtrVT, 8702 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 8703 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 8704 } 8705 8706 // Calculate the start address of the spliced result. 8707 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 8708 8709 // Load the spliced result 8710 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 8711 MachinePointerInfo::getUnknownStack(MF)); 8712 } 8713 8714 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 8715 SDValue &LHS, SDValue &RHS, 8716 SDValue &CC, bool &NeedInvert, 8717 const SDLoc &dl, SDValue &Chain, 8718 bool IsSignaling) const { 8719 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8720 MVT OpVT = LHS.getSimpleValueType(); 8721 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 8722 NeedInvert = false; 8723 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 8724 default: 8725 llvm_unreachable("Unknown condition code action!"); 8726 case TargetLowering::Legal: 8727 // Nothing to do. 8728 break; 8729 case TargetLowering::Expand: { 8730 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 8731 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8732 std::swap(LHS, RHS); 8733 CC = DAG.getCondCode(InvCC); 8734 return true; 8735 } 8736 // Swapping operands didn't work. Try inverting the condition. 8737 bool NeedSwap = false; 8738 InvCC = getSetCCInverse(CCCode, OpVT); 8739 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8740 // If inverting the condition is not enough, try swapping operands 8741 // on top of it. 8742 InvCC = ISD::getSetCCSwappedOperands(InvCC); 8743 NeedSwap = true; 8744 } 8745 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8746 CC = DAG.getCondCode(InvCC); 8747 NeedInvert = true; 8748 if (NeedSwap) 8749 std::swap(LHS, RHS); 8750 return true; 8751 } 8752 8753 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 8754 unsigned Opc = 0; 8755 switch (CCCode) { 8756 default: 8757 llvm_unreachable("Don't know how to expand this condition!"); 8758 case ISD::SETUO: 8759 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 8760 CC1 = ISD::SETUNE; 8761 CC2 = ISD::SETUNE; 8762 Opc = ISD::OR; 8763 break; 8764 } 8765 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 8766 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 8767 NeedInvert = true; 8768 LLVM_FALLTHROUGH; 8769 case ISD::SETO: 8770 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 8771 "If SETO is expanded, SETOEQ must be legal!"); 8772 CC1 = ISD::SETOEQ; 8773 CC2 = ISD::SETOEQ; 8774 Opc = ISD::AND; 8775 break; 8776 case ISD::SETONE: 8777 case ISD::SETUEQ: 8778 // If the SETUO or SETO CC isn't legal, we might be able to use 8779 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 8780 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 8781 // the operands. 8782 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 8783 if (!TLI.isCondCodeLegal(CC2, OpVT) && 8784 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 8785 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 8786 CC1 = ISD::SETOGT; 8787 CC2 = ISD::SETOLT; 8788 Opc = ISD::OR; 8789 NeedInvert = ((unsigned)CCCode & 0x8U); 8790 break; 8791 } 8792 LLVM_FALLTHROUGH; 8793 case ISD::SETOEQ: 8794 case ISD::SETOGT: 8795 case ISD::SETOGE: 8796 case ISD::SETOLT: 8797 case ISD::SETOLE: 8798 case ISD::SETUNE: 8799 case ISD::SETUGT: 8800 case ISD::SETUGE: 8801 case ISD::SETULT: 8802 case ISD::SETULE: 8803 // If we are floating point, assign and break, otherwise fall through. 8804 if (!OpVT.isInteger()) { 8805 // We can use the 4th bit to tell if we are the unordered 8806 // or ordered version of the opcode. 8807 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 8808 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 8809 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 8810 break; 8811 } 8812 // Fallthrough if we are unsigned integer. 8813 LLVM_FALLTHROUGH; 8814 case ISD::SETLE: 8815 case ISD::SETGT: 8816 case ISD::SETGE: 8817 case ISD::SETLT: 8818 case ISD::SETNE: 8819 case ISD::SETEQ: 8820 // If all combinations of inverting the condition and swapping operands 8821 // didn't work then we have no means to expand the condition. 8822 llvm_unreachable("Don't know how to expand this condition!"); 8823 } 8824 8825 SDValue SetCC1, SetCC2; 8826 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 8827 // If we aren't the ordered or unorder operation, 8828 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 8829 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 8830 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 8831 } else { 8832 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 8833 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 8834 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 8835 } 8836 if (Chain) 8837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 8838 SetCC2.getValue(1)); 8839 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 8840 RHS = SDValue(); 8841 CC = SDValue(); 8842 return true; 8843 } 8844 } 8845 return false; 8846 } 8847