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/CodeGenCommonISel.h" 17 #include "llvm/CodeGen/MachineFrameInfo.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineJumpTableInfo.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/SelectionDAG.h" 22 #include "llvm/CodeGen/TargetRegisterInfo.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/DivisionByConstantInfo.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/KnownBits.h" 32 #include "llvm/Support/MathExtras.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 following attributes because they don't affect the 61 // call sequence. 62 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 63 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable, 64 Attribute::DereferenceableOrNull, Attribute::NoAlias, 65 Attribute::NonNull, Attribute::NoUndef}) 66 CallerAttrs.removeAttribute(Attr); 67 68 if (CallerAttrs.hasAttributes()) 69 return false; 70 71 // It's not safe to eliminate the sign / zero extension of the return value. 72 if (CallerAttrs.contains(Attribute::ZExt) || 73 CallerAttrs.contains(Attribute::SExt)) 74 return false; 75 76 // Check if the only use is a function return node. 77 return isUsedByReturnOnly(Node, Chain); 78 } 79 80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 81 const uint32_t *CallerPreservedMask, 82 const SmallVectorImpl<CCValAssign> &ArgLocs, 83 const SmallVectorImpl<SDValue> &OutVals) const { 84 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 85 const CCValAssign &ArgLoc = ArgLocs[I]; 86 if (!ArgLoc.isRegLoc()) 87 continue; 88 MCRegister Reg = ArgLoc.getLocReg(); 89 // Only look at callee saved registers. 90 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 91 continue; 92 // Check that we pass the value used for the caller. 93 // (We look for a CopyFromReg reading a virtual register that is used 94 // for the function live-in value of register Reg) 95 SDValue Value = OutVals[I]; 96 if (Value->getOpcode() == ISD::AssertZext) 97 Value = Value.getOperand(0); 98 if (Value->getOpcode() != ISD::CopyFromReg) 99 return false; 100 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 101 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 102 return false; 103 } 104 return true; 105 } 106 107 /// Set CallLoweringInfo attribute flags based on a call instruction 108 /// and called function attributes. 109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 110 unsigned ArgIdx) { 111 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 112 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 113 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 114 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 115 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 116 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 117 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 118 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 119 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 120 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 121 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 122 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 123 Alignment = Call->getParamStackAlign(ArgIdx); 124 IndirectType = nullptr; 125 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 126 "multiple ABI attributes?"); 127 if (IsByVal) { 128 IndirectType = Call->getParamByValType(ArgIdx); 129 if (!Alignment) 130 Alignment = Call->getParamAlign(ArgIdx); 131 } 132 if (IsPreallocated) 133 IndirectType = Call->getParamPreallocatedType(ArgIdx); 134 if (IsInAlloca) 135 IndirectType = Call->getParamInAllocaType(ArgIdx); 136 if (IsSRet) 137 IndirectType = Call->getParamStructRetType(ArgIdx); 138 } 139 140 /// Generate a libcall taking the given operands as arguments and returning a 141 /// result of type RetVT. 142 std::pair<SDValue, SDValue> 143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 144 ArrayRef<SDValue> Ops, 145 MakeLibCallOptions CallOptions, 146 const SDLoc &dl, 147 SDValue InChain) const { 148 if (!InChain) 149 InChain = DAG.getEntryNode(); 150 151 TargetLowering::ArgListTy Args; 152 Args.reserve(Ops.size()); 153 154 TargetLowering::ArgListEntry Entry; 155 for (unsigned i = 0; i < Ops.size(); ++i) { 156 SDValue NewOp = Ops[i]; 157 Entry.Node = NewOp; 158 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 159 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 160 CallOptions.IsSExt); 161 Entry.IsZExt = !Entry.IsSExt; 162 163 if (CallOptions.IsSoften && 164 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 165 Entry.IsSExt = Entry.IsZExt = false; 166 } 167 Args.push_back(Entry); 168 } 169 170 if (LC == RTLIB::UNKNOWN_LIBCALL) 171 report_fatal_error("Unsupported library call operation!"); 172 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 173 getPointerTy(DAG.getDataLayout())); 174 175 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 176 TargetLowering::CallLoweringInfo CLI(DAG); 177 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 178 bool zeroExtend = !signExtend; 179 180 if (CallOptions.IsSoften && 181 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 182 signExtend = zeroExtend = false; 183 } 184 185 CLI.setDebugLoc(dl) 186 .setChain(InChain) 187 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 188 .setNoReturn(CallOptions.DoesNotReturn) 189 .setDiscardResult(!CallOptions.IsReturnValueUsed) 190 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 191 .setSExtResult(signExtend) 192 .setZExtResult(zeroExtend); 193 return LowerCallTo(CLI); 194 } 195 196 bool TargetLowering::findOptimalMemOpLowering( 197 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 198 unsigned SrcAS, const AttributeList &FuncAttributes) const { 199 if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() && 200 Op.getSrcAlign() < Op.getDstAlign()) 201 return false; 202 203 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 204 205 if (VT == MVT::Other) { 206 // Use the largest integer type whose alignment constraints are satisfied. 207 // We only need to check DstAlign here as SrcAlign is always greater or 208 // equal to DstAlign (or zero). 209 VT = MVT::i64; 210 if (Op.isFixedDstAlign()) 211 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 212 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 213 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 214 assert(VT.isInteger()); 215 216 // Find the largest legal integer type. 217 MVT LVT = MVT::i64; 218 while (!isTypeLegal(LVT)) 219 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 220 assert(LVT.isInteger()); 221 222 // If the type we've chosen is larger than the largest legal integer type 223 // then use that instead. 224 if (VT.bitsGT(LVT)) 225 VT = LVT; 226 } 227 228 unsigned NumMemOps = 0; 229 uint64_t Size = Op.size(); 230 while (Size) { 231 unsigned VTSize = VT.getSizeInBits() / 8; 232 while (VTSize > Size) { 233 // For now, only use non-vector load / store's for the left-over pieces. 234 EVT NewVT = VT; 235 unsigned NewVTSize; 236 237 bool Found = false; 238 if (VT.isVector() || VT.isFloatingPoint()) { 239 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 240 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 241 isSafeMemOpType(NewVT.getSimpleVT())) 242 Found = true; 243 else if (NewVT == MVT::i64 && 244 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 245 isSafeMemOpType(MVT::f64)) { 246 // i64 is usually not legal on 32-bit targets, but f64 may be. 247 NewVT = MVT::f64; 248 Found = true; 249 } 250 } 251 252 if (!Found) { 253 do { 254 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 255 if (NewVT == MVT::i8) 256 break; 257 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 258 } 259 NewVTSize = NewVT.getSizeInBits() / 8; 260 261 // If the new VT cannot cover all of the remaining bits, then consider 262 // issuing a (or a pair of) unaligned and overlapping load / store. 263 bool Fast; 264 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 265 allowsMisalignedMemoryAccesses( 266 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 267 MachineMemOperand::MONone, &Fast) && 268 Fast) 269 VTSize = Size; 270 else { 271 VT = NewVT; 272 VTSize = NewVTSize; 273 } 274 } 275 276 if (++NumMemOps > Limit) 277 return false; 278 279 MemOps.push_back(VT); 280 Size -= VTSize; 281 } 282 283 return true; 284 } 285 286 /// Soften the operands of a comparison. This code is shared among BR_CC, 287 /// SELECT_CC, and SETCC handlers. 288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 289 SDValue &NewLHS, SDValue &NewRHS, 290 ISD::CondCode &CCCode, 291 const SDLoc &dl, const SDValue OldLHS, 292 const SDValue OldRHS) const { 293 SDValue Chain; 294 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 295 OldRHS, Chain); 296 } 297 298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 299 SDValue &NewLHS, SDValue &NewRHS, 300 ISD::CondCode &CCCode, 301 const SDLoc &dl, const SDValue OldLHS, 302 const SDValue OldRHS, 303 SDValue &Chain, 304 bool IsSignaling) const { 305 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 306 // not supporting it. We can update this code when libgcc provides such 307 // functions. 308 309 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 310 && "Unsupported setcc type!"); 311 312 // Expand into one or more soft-fp libcall(s). 313 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 314 bool ShouldInvertCC = false; 315 switch (CCCode) { 316 case ISD::SETEQ: 317 case ISD::SETOEQ: 318 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 319 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 320 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 321 break; 322 case ISD::SETNE: 323 case ISD::SETUNE: 324 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 325 (VT == MVT::f64) ? RTLIB::UNE_F64 : 326 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 327 break; 328 case ISD::SETGE: 329 case ISD::SETOGE: 330 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 331 (VT == MVT::f64) ? RTLIB::OGE_F64 : 332 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 333 break; 334 case ISD::SETLT: 335 case ISD::SETOLT: 336 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 337 (VT == MVT::f64) ? RTLIB::OLT_F64 : 338 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 339 break; 340 case ISD::SETLE: 341 case ISD::SETOLE: 342 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 343 (VT == MVT::f64) ? RTLIB::OLE_F64 : 344 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 345 break; 346 case ISD::SETGT: 347 case ISD::SETOGT: 348 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 349 (VT == MVT::f64) ? RTLIB::OGT_F64 : 350 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 351 break; 352 case ISD::SETO: 353 ShouldInvertCC = true; 354 LLVM_FALLTHROUGH; 355 case ISD::SETUO: 356 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 357 (VT == MVT::f64) ? RTLIB::UO_F64 : 358 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 359 break; 360 case ISD::SETONE: 361 // SETONE = O && UNE 362 ShouldInvertCC = true; 363 LLVM_FALLTHROUGH; 364 case ISD::SETUEQ: 365 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 366 (VT == MVT::f64) ? RTLIB::UO_F64 : 367 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 368 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 369 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 370 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 371 break; 372 default: 373 // Invert CC for unordered comparisons 374 ShouldInvertCC = true; 375 switch (CCCode) { 376 case ISD::SETULT: 377 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 378 (VT == MVT::f64) ? RTLIB::OGE_F64 : 379 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 380 break; 381 case ISD::SETULE: 382 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 383 (VT == MVT::f64) ? RTLIB::OGT_F64 : 384 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 385 break; 386 case ISD::SETUGT: 387 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 388 (VT == MVT::f64) ? RTLIB::OLE_F64 : 389 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 390 break; 391 case ISD::SETUGE: 392 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 393 (VT == MVT::f64) ? RTLIB::OLT_F64 : 394 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 395 break; 396 default: llvm_unreachable("Do not know how to soften this setcc!"); 397 } 398 } 399 400 // Use the target specific return value for comparions lib calls. 401 EVT RetVT = getCmpLibcallReturnType(); 402 SDValue Ops[2] = {NewLHS, NewRHS}; 403 TargetLowering::MakeLibCallOptions CallOptions; 404 EVT OpsVT[2] = { OldLHS.getValueType(), 405 OldRHS.getValueType() }; 406 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 407 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 408 NewLHS = Call.first; 409 NewRHS = DAG.getConstant(0, dl, RetVT); 410 411 CCCode = getCmpLibcallCC(LC1); 412 if (ShouldInvertCC) { 413 assert(RetVT.isInteger()); 414 CCCode = getSetCCInverse(CCCode, RetVT); 415 } 416 417 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 418 // Update Chain. 419 Chain = Call.second; 420 } else { 421 EVT SetCCVT = 422 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 423 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 424 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 425 CCCode = getCmpLibcallCC(LC2); 426 if (ShouldInvertCC) 427 CCCode = getSetCCInverse(CCCode, RetVT); 428 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 429 if (Chain) 430 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 431 Call2.second); 432 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 433 Tmp.getValueType(), Tmp, NewLHS); 434 NewRHS = SDValue(); 435 } 436 } 437 438 /// Return the entry encoding for a jump table in the current function. The 439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 440 unsigned TargetLowering::getJumpTableEncoding() const { 441 // In non-pic modes, just use the address of a block. 442 if (!isPositionIndependent()) 443 return MachineJumpTableInfo::EK_BlockAddress; 444 445 // In PIC mode, if the target supports a GPRel32 directive, use it. 446 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 447 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 448 449 // Otherwise, use a label difference. 450 return MachineJumpTableInfo::EK_LabelDifference32; 451 } 452 453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 454 SelectionDAG &DAG) const { 455 // If our PIC model is GP relative, use the global offset table as the base. 456 unsigned JTEncoding = getJumpTableEncoding(); 457 458 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 459 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 460 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 461 462 return Table; 463 } 464 465 /// This returns the relocation base for the given PIC jumptable, the same as 466 /// getPICJumpTableRelocBase, but as an MCExpr. 467 const MCExpr * 468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 469 unsigned JTI,MCContext &Ctx) const{ 470 // The normal PIC reloc base is the label at the start of the jump table. 471 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 472 } 473 474 bool 475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 476 const TargetMachine &TM = getTargetMachine(); 477 const GlobalValue *GV = GA->getGlobal(); 478 479 // If the address is not even local to this DSO we will have to load it from 480 // a got and then add the offset. 481 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 482 return false; 483 484 // If the code is position independent we will have to add a base register. 485 if (isPositionIndependent()) 486 return false; 487 488 // Otherwise we can do it. 489 return true; 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Optimization Methods 494 //===----------------------------------------------------------------------===// 495 496 /// If the specified instruction has a constant integer operand and there are 497 /// bits set in that constant that are not demanded, then clear those bits and 498 /// return true. 499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 500 const APInt &DemandedBits, 501 const APInt &DemandedElts, 502 TargetLoweringOpt &TLO) const { 503 SDLoc DL(Op); 504 unsigned Opcode = Op.getOpcode(); 505 506 // Do target-specific constant optimization. 507 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 508 return TLO.New.getNode(); 509 510 // FIXME: ISD::SELECT, ISD::SELECT_CC 511 switch (Opcode) { 512 default: 513 break; 514 case ISD::XOR: 515 case ISD::AND: 516 case ISD::OR: { 517 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 518 if (!Op1C || Op1C->isOpaque()) 519 return false; 520 521 // If this is a 'not' op, don't touch it because that's a canonical form. 522 const APInt &C = Op1C->getAPIntValue(); 523 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 524 return false; 525 526 if (!C.isSubsetOf(DemandedBits)) { 527 EVT VT = Op.getValueType(); 528 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 529 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 530 return TLO.CombineTo(Op, NewOp); 531 } 532 533 break; 534 } 535 } 536 537 return false; 538 } 539 540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 541 const APInt &DemandedBits, 542 TargetLoweringOpt &TLO) const { 543 EVT VT = Op.getValueType(); 544 APInt DemandedElts = VT.isVector() 545 ? APInt::getAllOnes(VT.getVectorNumElements()) 546 : APInt(1, 1); 547 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 548 } 549 550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 552 /// generalized for targets with other types of implicit widening casts. 553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 554 const APInt &Demanded, 555 TargetLoweringOpt &TLO) const { 556 assert(Op.getNumOperands() == 2 && 557 "ShrinkDemandedOp only supports binary operators!"); 558 assert(Op.getNode()->getNumValues() == 1 && 559 "ShrinkDemandedOp only supports nodes with one result!"); 560 561 SelectionDAG &DAG = TLO.DAG; 562 SDLoc dl(Op); 563 564 // Early return, as this function cannot handle vector types. 565 if (Op.getValueType().isVector()) 566 return false; 567 568 // Don't do this if the node has another user, which may require the 569 // full value. 570 if (!Op.getNode()->hasOneUse()) 571 return false; 572 573 // Search for the smallest integer type with free casts to and from 574 // Op's type. For expedience, just check power-of-2 integer types. 575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 576 unsigned DemandedSize = Demanded.getActiveBits(); 577 unsigned SmallVTBits = DemandedSize; 578 if (!isPowerOf2_32(SmallVTBits)) 579 SmallVTBits = NextPowerOf2(SmallVTBits); 580 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 581 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 582 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 583 TLI.isZExtFree(SmallVT, Op.getValueType())) { 584 // We found a type with free casts. 585 SDValue X = DAG.getNode( 586 Op.getOpcode(), dl, SmallVT, 587 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 588 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 589 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 590 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 591 return TLO.CombineTo(Op, Z); 592 } 593 } 594 return false; 595 } 596 597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 598 DAGCombinerInfo &DCI) const { 599 SelectionDAG &DAG = DCI.DAG; 600 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 601 !DCI.isBeforeLegalizeOps()); 602 KnownBits Known; 603 604 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 605 if (Simplified) { 606 DCI.AddToWorklist(Op.getNode()); 607 DCI.CommitTargetLoweringOpt(TLO); 608 } 609 return Simplified; 610 } 611 612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 613 const APInt &DemandedElts, 614 DAGCombinerInfo &DCI) const { 615 SelectionDAG &DAG = DCI.DAG; 616 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 617 !DCI.isBeforeLegalizeOps()); 618 KnownBits Known; 619 620 bool Simplified = 621 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 622 if (Simplified) { 623 DCI.AddToWorklist(Op.getNode()); 624 DCI.CommitTargetLoweringOpt(TLO); 625 } 626 return Simplified; 627 } 628 629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 630 KnownBits &Known, 631 TargetLoweringOpt &TLO, 632 unsigned Depth, 633 bool AssumeSingleUse) const { 634 EVT VT = Op.getValueType(); 635 636 // TODO: We can probably do more work on calculating the known bits and 637 // simplifying the operations for scalable vectors, but for now we just 638 // bail out. 639 if (VT.isScalableVector()) { 640 // Pretend we don't know anything for now. 641 Known = KnownBits(DemandedBits.getBitWidth()); 642 return false; 643 } 644 645 APInt DemandedElts = VT.isVector() 646 ? APInt::getAllOnes(VT.getVectorNumElements()) 647 : APInt(1, 1); 648 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 649 AssumeSingleUse); 650 } 651 652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 653 // TODO: Under what circumstances can we create nodes? Constant folding? 654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 655 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 656 SelectionDAG &DAG, unsigned Depth) const { 657 // Limit search depth. 658 if (Depth >= SelectionDAG::MaxRecursionDepth) 659 return SDValue(); 660 661 // Ignore UNDEFs. 662 if (Op.isUndef()) 663 return SDValue(); 664 665 // Not demanding any bits/elts from Op. 666 if (DemandedBits == 0 || DemandedElts == 0) 667 return DAG.getUNDEF(Op.getValueType()); 668 669 bool IsLE = DAG.getDataLayout().isLittleEndian(); 670 unsigned NumElts = DemandedElts.getBitWidth(); 671 unsigned BitWidth = DemandedBits.getBitWidth(); 672 KnownBits LHSKnown, RHSKnown; 673 switch (Op.getOpcode()) { 674 case ISD::BITCAST: { 675 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 676 EVT SrcVT = Src.getValueType(); 677 EVT DstVT = Op.getValueType(); 678 if (SrcVT == DstVT) 679 return Src; 680 681 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 682 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 683 if (NumSrcEltBits == NumDstEltBits) 684 if (SDValue V = SimplifyMultipleUseDemandedBits( 685 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 686 return DAG.getBitcast(DstVT, V); 687 688 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 689 unsigned Scale = NumDstEltBits / NumSrcEltBits; 690 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 691 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 692 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 693 for (unsigned i = 0; i != Scale; ++i) { 694 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 695 unsigned BitOffset = EltOffset * NumSrcEltBits; 696 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 697 if (!Sub.isZero()) { 698 DemandedSrcBits |= Sub; 699 for (unsigned j = 0; j != NumElts; ++j) 700 if (DemandedElts[j]) 701 DemandedSrcElts.setBit((j * Scale) + i); 702 } 703 } 704 705 if (SDValue V = SimplifyMultipleUseDemandedBits( 706 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 707 return DAG.getBitcast(DstVT, V); 708 } 709 710 // TODO - bigendian once we have test coverage. 711 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 712 unsigned Scale = NumSrcEltBits / NumDstEltBits; 713 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 714 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 715 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 716 for (unsigned i = 0; i != NumElts; ++i) 717 if (DemandedElts[i]) { 718 unsigned Offset = (i % Scale) * NumDstEltBits; 719 DemandedSrcBits.insertBits(DemandedBits, Offset); 720 DemandedSrcElts.setBit(i / Scale); 721 } 722 723 if (SDValue V = SimplifyMultipleUseDemandedBits( 724 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 725 return DAG.getBitcast(DstVT, V); 726 } 727 728 break; 729 } 730 case ISD::AND: { 731 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 732 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 733 734 // If all of the demanded bits are known 1 on one side, return the other. 735 // These bits cannot contribute to the result of the 'and' in this 736 // context. 737 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 738 return Op.getOperand(0); 739 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 740 return Op.getOperand(1); 741 break; 742 } 743 case ISD::OR: { 744 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 745 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 746 747 // If all of the demanded bits are known zero on one side, return the 748 // other. These bits cannot contribute to the result of the 'or' in this 749 // context. 750 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 751 return Op.getOperand(0); 752 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 753 return Op.getOperand(1); 754 break; 755 } 756 case ISD::XOR: { 757 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 758 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 759 760 // If all of the demanded bits are known zero on one side, return the 761 // other. 762 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 763 return Op.getOperand(0); 764 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 765 return Op.getOperand(1); 766 break; 767 } 768 case ISD::SHL: { 769 // If we are only demanding sign bits then we can use the shift source 770 // directly. 771 if (const APInt *MaxSA = 772 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 773 SDValue Op0 = Op.getOperand(0); 774 unsigned ShAmt = MaxSA->getZExtValue(); 775 unsigned NumSignBits = 776 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 777 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 778 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 779 return Op0; 780 } 781 break; 782 } 783 case ISD::SETCC: { 784 SDValue Op0 = Op.getOperand(0); 785 SDValue Op1 = Op.getOperand(1); 786 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 787 // If (1) we only need the sign-bit, (2) the setcc operands are the same 788 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 789 // -1, we may be able to bypass the setcc. 790 if (DemandedBits.isSignMask() && 791 Op0.getScalarValueSizeInBits() == BitWidth && 792 getBooleanContents(Op0.getValueType()) == 793 BooleanContent::ZeroOrNegativeOneBooleanContent) { 794 // If we're testing X < 0, then this compare isn't needed - just use X! 795 // FIXME: We're limiting to integer types here, but this should also work 796 // if we don't care about FP signed-zero. The use of SETLT with FP means 797 // that we don't care about NaNs. 798 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 799 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 800 return Op0; 801 } 802 break; 803 } 804 case ISD::SIGN_EXTEND_INREG: { 805 // If none of the extended bits are demanded, eliminate the sextinreg. 806 SDValue Op0 = Op.getOperand(0); 807 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 808 unsigned ExBits = ExVT.getScalarSizeInBits(); 809 if (DemandedBits.getActiveBits() <= ExBits) 810 return Op0; 811 // If the input is already sign extended, just drop the extension. 812 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 813 if (NumSignBits >= (BitWidth - ExBits + 1)) 814 return Op0; 815 break; 816 } 817 case ISD::ANY_EXTEND_VECTOR_INREG: 818 case ISD::SIGN_EXTEND_VECTOR_INREG: 819 case ISD::ZERO_EXTEND_VECTOR_INREG: { 820 // If we only want the lowest element and none of extended bits, then we can 821 // return the bitcasted source vector. 822 SDValue Src = Op.getOperand(0); 823 EVT SrcVT = Src.getValueType(); 824 EVT DstVT = Op.getValueType(); 825 if (IsLE && DemandedElts == 1 && 826 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 827 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 828 return DAG.getBitcast(DstVT, Src); 829 } 830 break; 831 } 832 case ISD::INSERT_VECTOR_ELT: { 833 // If we don't demand the inserted element, return the base vector. 834 SDValue Vec = Op.getOperand(0); 835 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 836 EVT VecVT = Vec.getValueType(); 837 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 838 !DemandedElts[CIdx->getZExtValue()]) 839 return Vec; 840 break; 841 } 842 case ISD::INSERT_SUBVECTOR: { 843 SDValue Vec = Op.getOperand(0); 844 SDValue Sub = Op.getOperand(1); 845 uint64_t Idx = Op.getConstantOperandVal(2); 846 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 847 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 848 // If we don't demand the inserted subvector, return the base vector. 849 if (DemandedSubElts == 0) 850 return Vec; 851 // If this simply widens the lowest subvector, see if we can do it earlier. 852 if (Idx == 0 && Vec.isUndef()) { 853 if (SDValue NewSub = SimplifyMultipleUseDemandedBits( 854 Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1)) 855 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 856 Op.getOperand(0), NewSub, Op.getOperand(2)); 857 } 858 break; 859 } 860 case ISD::VECTOR_SHUFFLE: { 861 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 862 863 // If all the demanded elts are from one operand and are inline, 864 // then we can use the operand directly. 865 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 866 for (unsigned i = 0; i != NumElts; ++i) { 867 int M = ShuffleMask[i]; 868 if (M < 0 || !DemandedElts[i]) 869 continue; 870 AllUndef = false; 871 IdentityLHS &= (M == (int)i); 872 IdentityRHS &= ((M - NumElts) == i); 873 } 874 875 if (AllUndef) 876 return DAG.getUNDEF(Op.getValueType()); 877 if (IdentityLHS) 878 return Op.getOperand(0); 879 if (IdentityRHS) 880 return Op.getOperand(1); 881 break; 882 } 883 default: 884 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 885 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 886 Op, DemandedBits, DemandedElts, DAG, Depth)) 887 return V; 888 break; 889 } 890 return SDValue(); 891 } 892 893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 894 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 895 unsigned Depth) const { 896 EVT VT = Op.getValueType(); 897 APInt DemandedElts = VT.isVector() 898 ? APInt::getAllOnes(VT.getVectorNumElements()) 899 : APInt(1, 1); 900 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 901 Depth); 902 } 903 904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 905 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 906 unsigned Depth) const { 907 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 908 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 909 Depth); 910 } 911 912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 913 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG, 915 const TargetLowering &TLI, 916 const APInt &DemandedBits, 917 const APInt &DemandedElts, 918 unsigned Depth) { 919 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 920 "SRL or SRA node is required here!"); 921 // Is the right shift using an immediate value of 1? 922 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 923 if (!N1C || !N1C->isOne()) 924 return SDValue(); 925 926 // We are looking for an avgfloor 927 // add(ext, ext) 928 // or one of these as a avgceil 929 // add(add(ext, ext), 1) 930 // add(add(ext, 1), ext) 931 // add(ext, add(ext, 1)) 932 SDValue Add = Op.getOperand(0); 933 if (Add.getOpcode() != ISD::ADD) 934 return SDValue(); 935 936 SDValue ExtOpA = Add.getOperand(0); 937 SDValue ExtOpB = Add.getOperand(1); 938 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) { 939 ConstantSDNode *ConstOp; 940 if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) && 941 ConstOp->isOne()) { 942 ExtOpA = Op2; 943 ExtOpB = Op3; 944 return true; 945 } 946 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 947 ConstOp->isOne()) { 948 ExtOpA = Op1; 949 ExtOpB = Op3; 950 return true; 951 } 952 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 953 ConstOp->isOne()) { 954 ExtOpA = Op1; 955 ExtOpB = Op2; 956 return true; 957 } 958 return false; 959 }; 960 bool IsCeil = 961 (ExtOpA.getOpcode() == ISD::ADD && 962 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) || 963 (ExtOpB.getOpcode() == ISD::ADD && 964 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA)); 965 966 // If the shift is signed (sra): 967 // - Needs >= 2 sign bit for both operands. 968 // - Needs >= 2 zero bits. 969 // If the shift is unsigned (srl): 970 // - Needs >= 1 zero bit for both operands. 971 // - Needs 1 demanded bit zero and >= 2 sign bits. 972 unsigned ShiftOpc = Op.getOpcode(); 973 bool IsSigned = false; 974 unsigned KnownBits; 975 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 976 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 977 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 978 unsigned NumZeroA = 979 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 980 unsigned NumZeroB = 981 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 982 unsigned NumZero = std::min(NumZeroA, NumZeroB); 983 984 switch (ShiftOpc) { 985 default: 986 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 987 case ISD::SRA: { 988 if (NumZero >= 2 && NumSigned < NumZero) { 989 IsSigned = false; 990 KnownBits = NumZero; 991 break; 992 } 993 if (NumSigned >= 1) { 994 IsSigned = true; 995 KnownBits = NumSigned; 996 break; 997 } 998 return SDValue(); 999 } 1000 case ISD::SRL: { 1001 if (NumZero >= 1 && NumSigned < NumZero) { 1002 IsSigned = false; 1003 KnownBits = NumZero; 1004 break; 1005 } 1006 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1007 IsSigned = true; 1008 KnownBits = NumSigned; 1009 break; 1010 } 1011 return SDValue(); 1012 } 1013 } 1014 1015 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1016 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1017 1018 // Find the smallest power-2 type that is legal for this vector size and 1019 // operation, given the original type size and the number of known sign/zero 1020 // bits. 1021 EVT VT = Op.getValueType(); 1022 unsigned MinWidth = 1023 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1024 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth)); 1025 if (VT.isVector()) 1026 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1027 if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) 1028 return SDValue(); 1029 1030 SDLoc DL(Op); 1031 SDValue ResultAVG = 1032 DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA), 1033 DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB)); 1034 return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT, 1035 ResultAVG); 1036 } 1037 1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1039 /// result of Op are ever used downstream. If we can use this information to 1040 /// simplify Op, create a new simplified DAG node and return true, returning the 1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1042 /// return a mask of Known bits for the expression (used to simplify the 1043 /// caller). The Known bits may only be accurate for those bits in the 1044 /// OriginalDemandedBits and OriginalDemandedElts. 1045 bool TargetLowering::SimplifyDemandedBits( 1046 SDValue Op, const APInt &OriginalDemandedBits, 1047 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1048 unsigned Depth, bool AssumeSingleUse) const { 1049 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1050 assert(Op.getScalarValueSizeInBits() == BitWidth && 1051 "Mask size mismatches value type size!"); 1052 1053 // Don't know anything. 1054 Known = KnownBits(BitWidth); 1055 1056 // TODO: We can probably do more work on calculating the known bits and 1057 // simplifying the operations for scalable vectors, but for now we just 1058 // bail out. 1059 if (Op.getValueType().isScalableVector()) 1060 return false; 1061 1062 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1063 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1064 assert((!Op.getValueType().isVector() || 1065 NumElts == Op.getValueType().getVectorNumElements()) && 1066 "Unexpected vector size"); 1067 1068 APInt DemandedBits = OriginalDemandedBits; 1069 APInt DemandedElts = OriginalDemandedElts; 1070 SDLoc dl(Op); 1071 auto &DL = TLO.DAG.getDataLayout(); 1072 1073 // Undef operand. 1074 if (Op.isUndef()) 1075 return false; 1076 1077 if (Op.getOpcode() == ISD::Constant) { 1078 // We know all of the bits for a constant! 1079 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 1080 return false; 1081 } 1082 1083 if (Op.getOpcode() == ISD::ConstantFP) { 1084 // We know all of the bits for a floating point constant! 1085 Known = KnownBits::makeConstant( 1086 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1087 return false; 1088 } 1089 1090 // Other users may use these bits. 1091 EVT VT = Op.getValueType(); 1092 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 1093 if (Depth != 0) { 1094 // If not at the root, Just compute the Known bits to 1095 // simplify things downstream. 1096 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1097 return false; 1098 } 1099 // If this is the root being simplified, allow it to have multiple uses, 1100 // just set the DemandedBits/Elts to all bits. 1101 DemandedBits = APInt::getAllOnes(BitWidth); 1102 DemandedElts = APInt::getAllOnes(NumElts); 1103 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1104 // Not demanding any bits/elts from Op. 1105 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1106 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1107 // Limit search depth. 1108 return false; 1109 } 1110 1111 KnownBits Known2; 1112 switch (Op.getOpcode()) { 1113 case ISD::TargetConstant: 1114 llvm_unreachable("Can't simplify this node"); 1115 case ISD::SCALAR_TO_VECTOR: { 1116 if (!DemandedElts[0]) 1117 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1118 1119 KnownBits SrcKnown; 1120 SDValue Src = Op.getOperand(0); 1121 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1122 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1123 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1124 return true; 1125 1126 // Upper elements are undef, so only get the knownbits if we just demand 1127 // the bottom element. 1128 if (DemandedElts == 1) 1129 Known = SrcKnown.anyextOrTrunc(BitWidth); 1130 break; 1131 } 1132 case ISD::BUILD_VECTOR: 1133 // Collect the known bits that are shared by every demanded element. 1134 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1135 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1136 return false; // Don't fall through, will infinitely loop. 1137 case ISD::LOAD: { 1138 auto *LD = cast<LoadSDNode>(Op); 1139 if (getTargetConstantFromLoad(LD)) { 1140 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1141 return false; // Don't fall through, will infinitely loop. 1142 } 1143 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1144 // If this is a ZEXTLoad and we are looking at the loaded value. 1145 EVT MemVT = LD->getMemoryVT(); 1146 unsigned MemBits = MemVT.getScalarSizeInBits(); 1147 Known.Zero.setBitsFrom(MemBits); 1148 return false; // Don't fall through, will infinitely loop. 1149 } 1150 break; 1151 } 1152 case ISD::INSERT_VECTOR_ELT: { 1153 SDValue Vec = Op.getOperand(0); 1154 SDValue Scl = Op.getOperand(1); 1155 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1156 EVT VecVT = Vec.getValueType(); 1157 1158 // If index isn't constant, assume we need all vector elements AND the 1159 // inserted element. 1160 APInt DemandedVecElts(DemandedElts); 1161 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1162 unsigned Idx = CIdx->getZExtValue(); 1163 DemandedVecElts.clearBit(Idx); 1164 1165 // Inserted element is not required. 1166 if (!DemandedElts[Idx]) 1167 return TLO.CombineTo(Op, Vec); 1168 } 1169 1170 KnownBits KnownScl; 1171 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1172 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1173 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1174 return true; 1175 1176 Known = KnownScl.anyextOrTrunc(BitWidth); 1177 1178 KnownBits KnownVec; 1179 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1180 Depth + 1)) 1181 return true; 1182 1183 if (!!DemandedVecElts) 1184 Known = KnownBits::commonBits(Known, KnownVec); 1185 1186 return false; 1187 } 1188 case ISD::INSERT_SUBVECTOR: { 1189 // Demand any elements from the subvector and the remainder from the src its 1190 // inserted into. 1191 SDValue Src = Op.getOperand(0); 1192 SDValue Sub = Op.getOperand(1); 1193 uint64_t Idx = Op.getConstantOperandVal(2); 1194 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1195 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1196 APInt DemandedSrcElts = DemandedElts; 1197 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1198 1199 KnownBits KnownSub, KnownSrc; 1200 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1201 Depth + 1)) 1202 return true; 1203 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1204 Depth + 1)) 1205 return true; 1206 1207 Known.Zero.setAllBits(); 1208 Known.One.setAllBits(); 1209 if (!!DemandedSubElts) 1210 Known = KnownBits::commonBits(Known, KnownSub); 1211 if (!!DemandedSrcElts) 1212 Known = KnownBits::commonBits(Known, KnownSrc); 1213 1214 // Attempt to avoid multi-use src if we don't need anything from it. 1215 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1216 !DemandedSrcElts.isAllOnes()) { 1217 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1218 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1219 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1220 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1221 if (NewSub || NewSrc) { 1222 NewSub = NewSub ? NewSub : Sub; 1223 NewSrc = NewSrc ? NewSrc : Src; 1224 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1225 Op.getOperand(2)); 1226 return TLO.CombineTo(Op, NewOp); 1227 } 1228 } 1229 break; 1230 } 1231 case ISD::EXTRACT_SUBVECTOR: { 1232 // Offset the demanded elts by the subvector index. 1233 SDValue Src = Op.getOperand(0); 1234 if (Src.getValueType().isScalableVector()) 1235 break; 1236 uint64_t Idx = Op.getConstantOperandVal(1); 1237 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1238 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1239 1240 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1241 Depth + 1)) 1242 return true; 1243 1244 // Attempt to avoid multi-use src if we don't need anything from it. 1245 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1246 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1247 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1248 if (DemandedSrc) { 1249 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1250 Op.getOperand(1)); 1251 return TLO.CombineTo(Op, NewOp); 1252 } 1253 } 1254 break; 1255 } 1256 case ISD::CONCAT_VECTORS: { 1257 Known.Zero.setAllBits(); 1258 Known.One.setAllBits(); 1259 EVT SubVT = Op.getOperand(0).getValueType(); 1260 unsigned NumSubVecs = Op.getNumOperands(); 1261 unsigned NumSubElts = SubVT.getVectorNumElements(); 1262 for (unsigned i = 0; i != NumSubVecs; ++i) { 1263 APInt DemandedSubElts = 1264 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1265 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1266 Known2, TLO, Depth + 1)) 1267 return true; 1268 // Known bits are shared by every demanded subvector element. 1269 if (!!DemandedSubElts) 1270 Known = KnownBits::commonBits(Known, Known2); 1271 } 1272 break; 1273 } 1274 case ISD::VECTOR_SHUFFLE: { 1275 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1276 1277 // Collect demanded elements from shuffle operands.. 1278 APInt DemandedLHS(NumElts, 0); 1279 APInt DemandedRHS(NumElts, 0); 1280 for (unsigned i = 0; i != NumElts; ++i) { 1281 if (!DemandedElts[i]) 1282 continue; 1283 int M = ShuffleMask[i]; 1284 if (M < 0) { 1285 // For UNDEF elements, we don't know anything about the common state of 1286 // the shuffle result. 1287 DemandedLHS.clearAllBits(); 1288 DemandedRHS.clearAllBits(); 1289 break; 1290 } 1291 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1292 if (M < (int)NumElts) 1293 DemandedLHS.setBit(M); 1294 else 1295 DemandedRHS.setBit(M - NumElts); 1296 } 1297 1298 if (!!DemandedLHS || !!DemandedRHS) { 1299 SDValue Op0 = Op.getOperand(0); 1300 SDValue Op1 = Op.getOperand(1); 1301 1302 Known.Zero.setAllBits(); 1303 Known.One.setAllBits(); 1304 if (!!DemandedLHS) { 1305 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1306 Depth + 1)) 1307 return true; 1308 Known = KnownBits::commonBits(Known, Known2); 1309 } 1310 if (!!DemandedRHS) { 1311 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1312 Depth + 1)) 1313 return true; 1314 Known = KnownBits::commonBits(Known, Known2); 1315 } 1316 1317 // Attempt to avoid multi-use ops if we don't need anything from them. 1318 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1319 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1320 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1321 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1322 if (DemandedOp0 || DemandedOp1) { 1323 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1324 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1325 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1326 return TLO.CombineTo(Op, NewOp); 1327 } 1328 } 1329 break; 1330 } 1331 case ISD::AND: { 1332 SDValue Op0 = Op.getOperand(0); 1333 SDValue Op1 = Op.getOperand(1); 1334 1335 // If the RHS is a constant, check to see if the LHS would be zero without 1336 // using the bits from the RHS. Below, we use knowledge about the RHS to 1337 // simplify the LHS, here we're using information from the LHS to simplify 1338 // the RHS. 1339 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1340 // Do not increment Depth here; that can cause an infinite loop. 1341 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1342 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1343 if ((LHSKnown.Zero & DemandedBits) == 1344 (~RHSC->getAPIntValue() & DemandedBits)) 1345 return TLO.CombineTo(Op, Op0); 1346 1347 // If any of the set bits in the RHS are known zero on the LHS, shrink 1348 // the constant. 1349 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1350 DemandedElts, TLO)) 1351 return true; 1352 1353 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1354 // constant, but if this 'and' is only clearing bits that were just set by 1355 // the xor, then this 'and' can be eliminated by shrinking the mask of 1356 // the xor. For example, for a 32-bit X: 1357 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1358 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1359 LHSKnown.One == ~RHSC->getAPIntValue()) { 1360 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1361 return TLO.CombineTo(Op, Xor); 1362 } 1363 } 1364 1365 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1366 Depth + 1)) 1367 return true; 1368 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1369 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1370 Known2, TLO, Depth + 1)) 1371 return true; 1372 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1373 1374 // Attempt to avoid multi-use ops if we don't need anything from them. 1375 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1376 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1377 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1378 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1379 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1380 if (DemandedOp0 || DemandedOp1) { 1381 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1382 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1383 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1384 return TLO.CombineTo(Op, NewOp); 1385 } 1386 } 1387 1388 // If all of the demanded bits are known one on one side, return the other. 1389 // These bits cannot contribute to the result of the 'and'. 1390 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1391 return TLO.CombineTo(Op, Op0); 1392 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1393 return TLO.CombineTo(Op, Op1); 1394 // If all of the demanded bits in the inputs are known zeros, return zero. 1395 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1396 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1397 // If the RHS is a constant, see if we can simplify it. 1398 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1399 TLO)) 1400 return true; 1401 // If the operation can be done in a smaller type, do so. 1402 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1403 return true; 1404 1405 Known &= Known2; 1406 break; 1407 } 1408 case ISD::OR: { 1409 SDValue Op0 = Op.getOperand(0); 1410 SDValue Op1 = Op.getOperand(1); 1411 1412 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1413 Depth + 1)) 1414 return true; 1415 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1416 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1417 Known2, TLO, Depth + 1)) 1418 return true; 1419 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1420 1421 // Attempt to avoid multi-use ops if we don't need anything from them. 1422 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1423 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1424 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1425 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1426 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1427 if (DemandedOp0 || DemandedOp1) { 1428 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1429 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1430 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1431 return TLO.CombineTo(Op, NewOp); 1432 } 1433 } 1434 1435 // If all of the demanded bits are known zero on one side, return the other. 1436 // These bits cannot contribute to the result of the 'or'. 1437 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1438 return TLO.CombineTo(Op, Op0); 1439 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1440 return TLO.CombineTo(Op, Op1); 1441 // If the RHS is a constant, see if we can simplify it. 1442 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1443 return true; 1444 // If the operation can be done in a smaller type, do so. 1445 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1446 return true; 1447 1448 Known |= Known2; 1449 break; 1450 } 1451 case ISD::XOR: { 1452 SDValue Op0 = Op.getOperand(0); 1453 SDValue Op1 = Op.getOperand(1); 1454 1455 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1456 Depth + 1)) 1457 return true; 1458 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1459 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1460 Depth + 1)) 1461 return true; 1462 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1463 1464 // Attempt to avoid multi-use ops if we don't need anything from them. 1465 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1466 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1467 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1468 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1469 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1470 if (DemandedOp0 || DemandedOp1) { 1471 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1472 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1473 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1474 return TLO.CombineTo(Op, NewOp); 1475 } 1476 } 1477 1478 // If all of the demanded bits are known zero on one side, return the other. 1479 // These bits cannot contribute to the result of the 'xor'. 1480 if (DemandedBits.isSubsetOf(Known.Zero)) 1481 return TLO.CombineTo(Op, Op0); 1482 if (DemandedBits.isSubsetOf(Known2.Zero)) 1483 return TLO.CombineTo(Op, Op1); 1484 // If the operation can be done in a smaller type, do so. 1485 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1486 return true; 1487 1488 // If all of the unknown bits are known to be zero on one side or the other 1489 // turn this into an *inclusive* or. 1490 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1491 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1492 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1493 1494 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1495 if (C) { 1496 // If one side is a constant, and all of the set bits in the constant are 1497 // also known set on the other side, turn this into an AND, as we know 1498 // the bits will be cleared. 1499 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1500 // NB: it is okay if more bits are known than are requested 1501 if (C->getAPIntValue() == Known2.One) { 1502 SDValue ANDC = 1503 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1504 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1505 } 1506 1507 // If the RHS is a constant, see if we can change it. Don't alter a -1 1508 // constant because that's a 'not' op, and that is better for combining 1509 // and codegen. 1510 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1511 // We're flipping all demanded bits. Flip the undemanded bits too. 1512 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1513 return TLO.CombineTo(Op, New); 1514 } 1515 } 1516 1517 // If we can't turn this into a 'not', try to shrink the constant. 1518 if (!C || !C->isAllOnes()) 1519 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1520 return true; 1521 1522 Known ^= Known2; 1523 break; 1524 } 1525 case ISD::SELECT: 1526 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1527 Depth + 1)) 1528 return true; 1529 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1530 Depth + 1)) 1531 return true; 1532 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1533 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1534 1535 // If the operands are constants, see if we can simplify them. 1536 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1537 return true; 1538 1539 // Only known if known in both the LHS and RHS. 1540 Known = KnownBits::commonBits(Known, Known2); 1541 break; 1542 case ISD::SELECT_CC: 1543 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1544 Depth + 1)) 1545 return true; 1546 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1547 Depth + 1)) 1548 return true; 1549 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1550 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1551 1552 // If the operands are constants, see if we can simplify them. 1553 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1554 return true; 1555 1556 // Only known if known in both the LHS and RHS. 1557 Known = KnownBits::commonBits(Known, Known2); 1558 break; 1559 case ISD::SETCC: { 1560 SDValue Op0 = Op.getOperand(0); 1561 SDValue Op1 = Op.getOperand(1); 1562 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1563 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1564 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1565 // -1, we may be able to bypass the setcc. 1566 if (DemandedBits.isSignMask() && 1567 Op0.getScalarValueSizeInBits() == BitWidth && 1568 getBooleanContents(Op0.getValueType()) == 1569 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1570 // If we're testing X < 0, then this compare isn't needed - just use X! 1571 // FIXME: We're limiting to integer types here, but this should also work 1572 // if we don't care about FP signed-zero. The use of SETLT with FP means 1573 // that we don't care about NaNs. 1574 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1575 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1576 return TLO.CombineTo(Op, Op0); 1577 1578 // TODO: Should we check for other forms of sign-bit comparisons? 1579 // Examples: X <= -1, X >= 0 1580 } 1581 if (getBooleanContents(Op0.getValueType()) == 1582 TargetLowering::ZeroOrOneBooleanContent && 1583 BitWidth > 1) 1584 Known.Zero.setBitsFrom(1); 1585 break; 1586 } 1587 case ISD::SHL: { 1588 SDValue Op0 = Op.getOperand(0); 1589 SDValue Op1 = Op.getOperand(1); 1590 EVT ShiftVT = Op1.getValueType(); 1591 1592 if (const APInt *SA = 1593 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1594 unsigned ShAmt = SA->getZExtValue(); 1595 if (ShAmt == 0) 1596 return TLO.CombineTo(Op, Op0); 1597 1598 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1599 // single shift. We can do this if the bottom bits (which are shifted 1600 // out) are never demanded. 1601 // TODO - support non-uniform vector amounts. 1602 if (Op0.getOpcode() == ISD::SRL) { 1603 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1604 if (const APInt *SA2 = 1605 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1606 unsigned C1 = SA2->getZExtValue(); 1607 unsigned Opc = ISD::SHL; 1608 int Diff = ShAmt - C1; 1609 if (Diff < 0) { 1610 Diff = -Diff; 1611 Opc = ISD::SRL; 1612 } 1613 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1614 return TLO.CombineTo( 1615 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1616 } 1617 } 1618 } 1619 1620 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1621 // are not demanded. This will likely allow the anyext to be folded away. 1622 // TODO - support non-uniform vector amounts. 1623 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1624 SDValue InnerOp = Op0.getOperand(0); 1625 EVT InnerVT = InnerOp.getValueType(); 1626 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1627 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1628 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1629 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1630 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1631 ShTy = InnerVT; 1632 SDValue NarrowShl = 1633 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1634 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1635 return TLO.CombineTo( 1636 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1637 } 1638 1639 // Repeat the SHL optimization above in cases where an extension 1640 // intervenes: (shl (anyext (shr x, c1)), c2) to 1641 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1642 // aren't demanded (as above) and that the shifted upper c1 bits of 1643 // x aren't demanded. 1644 // TODO - support non-uniform vector amounts. 1645 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1646 InnerOp.hasOneUse()) { 1647 if (const APInt *SA2 = 1648 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1649 unsigned InnerShAmt = SA2->getZExtValue(); 1650 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1651 DemandedBits.getActiveBits() <= 1652 (InnerBits - InnerShAmt + ShAmt) && 1653 DemandedBits.countTrailingZeros() >= ShAmt) { 1654 SDValue NewSA = 1655 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1656 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1657 InnerOp.getOperand(0)); 1658 return TLO.CombineTo( 1659 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1660 } 1661 } 1662 } 1663 } 1664 1665 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1666 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1667 Depth + 1)) 1668 return true; 1669 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1670 Known.Zero <<= ShAmt; 1671 Known.One <<= ShAmt; 1672 // low bits known zero. 1673 Known.Zero.setLowBits(ShAmt); 1674 1675 // Attempt to avoid multi-use ops if we don't need anything from them. 1676 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1677 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1678 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1679 if (DemandedOp0) { 1680 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1681 return TLO.CombineTo(Op, NewOp); 1682 } 1683 } 1684 1685 // Try shrinking the operation as long as the shift amount will still be 1686 // in range. 1687 if ((ShAmt < DemandedBits.getActiveBits()) && 1688 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1689 return true; 1690 } 1691 1692 // If we are only demanding sign bits then we can use the shift source 1693 // directly. 1694 if (const APInt *MaxSA = 1695 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1696 unsigned ShAmt = MaxSA->getZExtValue(); 1697 unsigned NumSignBits = 1698 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1699 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1700 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1701 return TLO.CombineTo(Op, Op0); 1702 } 1703 break; 1704 } 1705 case ISD::SRL: { 1706 SDValue Op0 = Op.getOperand(0); 1707 SDValue Op1 = Op.getOperand(1); 1708 EVT ShiftVT = Op1.getValueType(); 1709 1710 // Try to match AVG patterns. 1711 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1712 DemandedElts, Depth + 1)) 1713 return TLO.CombineTo(Op, AVG); 1714 1715 if (const APInt *SA = 1716 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1717 unsigned ShAmt = SA->getZExtValue(); 1718 if (ShAmt == 0) 1719 return TLO.CombineTo(Op, Op0); 1720 1721 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1722 // single shift. We can do this if the top bits (which are shifted out) 1723 // are never demanded. 1724 // TODO - support non-uniform vector amounts. 1725 if (Op0.getOpcode() == ISD::SHL) { 1726 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1727 if (const APInt *SA2 = 1728 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1729 unsigned C1 = SA2->getZExtValue(); 1730 unsigned Opc = ISD::SRL; 1731 int Diff = ShAmt - C1; 1732 if (Diff < 0) { 1733 Diff = -Diff; 1734 Opc = ISD::SHL; 1735 } 1736 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1737 return TLO.CombineTo( 1738 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1739 } 1740 } 1741 } 1742 1743 APInt InDemandedMask = (DemandedBits << ShAmt); 1744 1745 // If the shift is exact, then it does demand the low bits (and knows that 1746 // they are zero). 1747 if (Op->getFlags().hasExact()) 1748 InDemandedMask.setLowBits(ShAmt); 1749 1750 // Compute the new bits that are at the top now. 1751 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1752 Depth + 1)) 1753 return true; 1754 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1755 Known.Zero.lshrInPlace(ShAmt); 1756 Known.One.lshrInPlace(ShAmt); 1757 // High bits known zero. 1758 Known.Zero.setHighBits(ShAmt); 1759 } 1760 break; 1761 } 1762 case ISD::SRA: { 1763 SDValue Op0 = Op.getOperand(0); 1764 SDValue Op1 = Op.getOperand(1); 1765 EVT ShiftVT = Op1.getValueType(); 1766 1767 // If we only want bits that already match the signbit then we don't need 1768 // to shift. 1769 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1770 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1771 NumHiDemandedBits) 1772 return TLO.CombineTo(Op, Op0); 1773 1774 // If this is an arithmetic shift right and only the low-bit is set, we can 1775 // always convert this into a logical shr, even if the shift amount is 1776 // variable. The low bit of the shift cannot be an input sign bit unless 1777 // the shift amount is >= the size of the datatype, which is undefined. 1778 if (DemandedBits.isOne()) 1779 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1780 1781 // Try to match AVG patterns. 1782 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1783 DemandedElts, Depth + 1)) 1784 return TLO.CombineTo(Op, AVG); 1785 1786 if (const APInt *SA = 1787 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1788 unsigned ShAmt = SA->getZExtValue(); 1789 if (ShAmt == 0) 1790 return TLO.CombineTo(Op, Op0); 1791 1792 APInt InDemandedMask = (DemandedBits << ShAmt); 1793 1794 // If the shift is exact, then it does demand the low bits (and knows that 1795 // they are zero). 1796 if (Op->getFlags().hasExact()) 1797 InDemandedMask.setLowBits(ShAmt); 1798 1799 // If any of the demanded bits are produced by the sign extension, we also 1800 // demand the input sign bit. 1801 if (DemandedBits.countLeadingZeros() < ShAmt) 1802 InDemandedMask.setSignBit(); 1803 1804 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1805 Depth + 1)) 1806 return true; 1807 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1808 Known.Zero.lshrInPlace(ShAmt); 1809 Known.One.lshrInPlace(ShAmt); 1810 1811 // If the input sign bit is known to be zero, or if none of the top bits 1812 // are demanded, turn this into an unsigned shift right. 1813 if (Known.Zero[BitWidth - ShAmt - 1] || 1814 DemandedBits.countLeadingZeros() >= ShAmt) { 1815 SDNodeFlags Flags; 1816 Flags.setExact(Op->getFlags().hasExact()); 1817 return TLO.CombineTo( 1818 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1819 } 1820 1821 int Log2 = DemandedBits.exactLogBase2(); 1822 if (Log2 >= 0) { 1823 // The bit must come from the sign. 1824 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1825 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1826 } 1827 1828 if (Known.One[BitWidth - ShAmt - 1]) 1829 // New bits are known one. 1830 Known.One.setHighBits(ShAmt); 1831 1832 // Attempt to avoid multi-use ops if we don't need anything from them. 1833 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1834 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1835 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1836 if (DemandedOp0) { 1837 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1838 return TLO.CombineTo(Op, NewOp); 1839 } 1840 } 1841 } 1842 break; 1843 } 1844 case ISD::FSHL: 1845 case ISD::FSHR: { 1846 SDValue Op0 = Op.getOperand(0); 1847 SDValue Op1 = Op.getOperand(1); 1848 SDValue Op2 = Op.getOperand(2); 1849 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1850 1851 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1852 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1853 1854 // For fshl, 0-shift returns the 1st arg. 1855 // For fshr, 0-shift returns the 2nd arg. 1856 if (Amt == 0) { 1857 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1858 Known, TLO, Depth + 1)) 1859 return true; 1860 break; 1861 } 1862 1863 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1864 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1865 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1866 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1867 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1868 Depth + 1)) 1869 return true; 1870 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1871 Depth + 1)) 1872 return true; 1873 1874 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1875 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1876 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1877 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1878 Known.One |= Known2.One; 1879 Known.Zero |= Known2.Zero; 1880 } 1881 1882 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1883 if (isPowerOf2_32(BitWidth)) { 1884 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1885 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1886 Known2, TLO, Depth + 1)) 1887 return true; 1888 } 1889 break; 1890 } 1891 case ISD::ROTL: 1892 case ISD::ROTR: { 1893 SDValue Op0 = Op.getOperand(0); 1894 SDValue Op1 = Op.getOperand(1); 1895 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1896 1897 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1898 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1899 return TLO.CombineTo(Op, Op0); 1900 1901 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 1902 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1903 unsigned RevAmt = BitWidth - Amt; 1904 1905 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 1906 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 1907 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 1908 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1909 Depth + 1)) 1910 return true; 1911 1912 // rot*(x, 0) --> x 1913 if (Amt == 0) 1914 return TLO.CombineTo(Op, Op0); 1915 1916 // See if we don't demand either half of the rotated bits. 1917 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 1918 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 1919 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 1920 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 1921 } 1922 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 1923 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 1924 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 1925 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1926 } 1927 } 1928 1929 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1930 if (isPowerOf2_32(BitWidth)) { 1931 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1932 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1933 Depth + 1)) 1934 return true; 1935 } 1936 break; 1937 } 1938 case ISD::UMIN: { 1939 // Check if one arg is always less than (or equal) to the other arg. 1940 SDValue Op0 = Op.getOperand(0); 1941 SDValue Op1 = Op.getOperand(1); 1942 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1943 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1944 Known = KnownBits::umin(Known0, Known1); 1945 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1946 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1947 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1948 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1949 break; 1950 } 1951 case ISD::UMAX: { 1952 // Check if one arg is always greater than (or equal) to the other arg. 1953 SDValue Op0 = Op.getOperand(0); 1954 SDValue Op1 = Op.getOperand(1); 1955 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1956 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1957 Known = KnownBits::umax(Known0, Known1); 1958 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1959 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1960 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1961 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1962 break; 1963 } 1964 case ISD::BITREVERSE: { 1965 SDValue Src = Op.getOperand(0); 1966 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1967 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1968 Depth + 1)) 1969 return true; 1970 Known.One = Known2.One.reverseBits(); 1971 Known.Zero = Known2.Zero.reverseBits(); 1972 break; 1973 } 1974 case ISD::BSWAP: { 1975 SDValue Src = Op.getOperand(0); 1976 1977 // If the only bits demanded come from one byte of the bswap result, 1978 // just shift the input byte into position to eliminate the bswap. 1979 unsigned NLZ = DemandedBits.countLeadingZeros(); 1980 unsigned NTZ = DemandedBits.countTrailingZeros(); 1981 1982 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 1983 // we need all the bits down to bit 8. Likewise, round NLZ. If we 1984 // have 14 leading zeros, round to 8. 1985 NLZ = alignDown(NLZ, 8); 1986 NTZ = alignDown(NTZ, 8); 1987 // If we need exactly one byte, we can do this transformation. 1988 if (BitWidth - NLZ - NTZ == 8) { 1989 // Replace this with either a left or right shift to get the byte into 1990 // the right place. 1991 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 1992 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 1993 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 1994 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 1995 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 1996 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 1997 return TLO.CombineTo(Op, NewOp); 1998 } 1999 } 2000 2001 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2002 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2003 Depth + 1)) 2004 return true; 2005 Known.One = Known2.One.byteSwap(); 2006 Known.Zero = Known2.Zero.byteSwap(); 2007 break; 2008 } 2009 case ISD::CTPOP: { 2010 // If only 1 bit is demanded, replace with PARITY as long as we're before 2011 // op legalization. 2012 // FIXME: Limit to scalars for now. 2013 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2014 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2015 Op.getOperand(0))); 2016 2017 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2018 break; 2019 } 2020 case ISD::SIGN_EXTEND_INREG: { 2021 SDValue Op0 = Op.getOperand(0); 2022 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2023 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2024 2025 // If we only care about the highest bit, don't bother shifting right. 2026 if (DemandedBits.isSignMask()) { 2027 unsigned MinSignedBits = 2028 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2029 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2030 // However if the input is already sign extended we expect the sign 2031 // extension to be dropped altogether later and do not simplify. 2032 if (!AlreadySignExtended) { 2033 // Compute the correct shift amount type, which must be getShiftAmountTy 2034 // for scalar types after legalization. 2035 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2036 getShiftAmountTy(VT, DL)); 2037 return TLO.CombineTo(Op, 2038 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2039 } 2040 } 2041 2042 // If none of the extended bits are demanded, eliminate the sextinreg. 2043 if (DemandedBits.getActiveBits() <= ExVTBits) 2044 return TLO.CombineTo(Op, Op0); 2045 2046 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2047 2048 // Since the sign extended bits are demanded, we know that the sign 2049 // bit is demanded. 2050 InputDemandedBits.setBit(ExVTBits - 1); 2051 2052 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 2053 return true; 2054 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2055 2056 // If the sign bit of the input is known set or clear, then we know the 2057 // top bits of the result. 2058 2059 // If the input sign bit is known zero, convert this into a zero extension. 2060 if (Known.Zero[ExVTBits - 1]) 2061 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2062 2063 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2064 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2065 Known.One.setBitsFrom(ExVTBits); 2066 Known.Zero &= Mask; 2067 } else { // Input sign bit unknown 2068 Known.Zero &= Mask; 2069 Known.One &= Mask; 2070 } 2071 break; 2072 } 2073 case ISD::BUILD_PAIR: { 2074 EVT HalfVT = Op.getOperand(0).getValueType(); 2075 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2076 2077 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2078 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2079 2080 KnownBits KnownLo, KnownHi; 2081 2082 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2083 return true; 2084 2085 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2086 return true; 2087 2088 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2089 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2090 2091 Known.One = KnownLo.One.zext(BitWidth) | 2092 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2093 break; 2094 } 2095 case ISD::ZERO_EXTEND: 2096 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2097 SDValue Src = Op.getOperand(0); 2098 EVT SrcVT = Src.getValueType(); 2099 unsigned InBits = SrcVT.getScalarSizeInBits(); 2100 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2101 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2102 2103 // If none of the top bits are demanded, convert this into an any_extend. 2104 if (DemandedBits.getActiveBits() <= InBits) { 2105 // If we only need the non-extended bits of the bottom element 2106 // then we can just bitcast to the result. 2107 if (IsLE && IsVecInReg && DemandedElts == 1 && 2108 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2109 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2110 2111 unsigned Opc = 2112 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2113 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2114 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2115 } 2116 2117 APInt InDemandedBits = DemandedBits.trunc(InBits); 2118 APInt InDemandedElts = DemandedElts.zext(InElts); 2119 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2120 Depth + 1)) 2121 return true; 2122 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2123 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2124 Known = Known.zext(BitWidth); 2125 2126 // Attempt to avoid multi-use ops if we don't need anything from them. 2127 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2128 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2129 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2130 break; 2131 } 2132 case ISD::SIGN_EXTEND: 2133 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2134 SDValue Src = Op.getOperand(0); 2135 EVT SrcVT = Src.getValueType(); 2136 unsigned InBits = SrcVT.getScalarSizeInBits(); 2137 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2138 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2139 2140 // If none of the top bits are demanded, convert this into an any_extend. 2141 if (DemandedBits.getActiveBits() <= InBits) { 2142 // If we only need the non-extended bits of the bottom element 2143 // then we can just bitcast to the result. 2144 if (IsLE && IsVecInReg && DemandedElts == 1 && 2145 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2146 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2147 2148 unsigned Opc = 2149 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2150 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2151 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2152 } 2153 2154 APInt InDemandedBits = DemandedBits.trunc(InBits); 2155 APInt InDemandedElts = DemandedElts.zext(InElts); 2156 2157 // Since some of the sign extended bits are demanded, we know that the sign 2158 // bit is demanded. 2159 InDemandedBits.setBit(InBits - 1); 2160 2161 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2162 Depth + 1)) 2163 return true; 2164 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2165 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2166 2167 // If the sign bit is known one, the top bits match. 2168 Known = Known.sext(BitWidth); 2169 2170 // If the sign bit is known zero, convert this to a zero extend. 2171 if (Known.isNonNegative()) { 2172 unsigned Opc = 2173 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2174 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2175 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2176 } 2177 2178 // Attempt to avoid multi-use ops if we don't need anything from them. 2179 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2180 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2181 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2182 break; 2183 } 2184 case ISD::ANY_EXTEND: 2185 case ISD::ANY_EXTEND_VECTOR_INREG: { 2186 SDValue Src = Op.getOperand(0); 2187 EVT SrcVT = Src.getValueType(); 2188 unsigned InBits = SrcVT.getScalarSizeInBits(); 2189 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2190 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2191 2192 // If we only need the bottom element then we can just bitcast. 2193 // TODO: Handle ANY_EXTEND? 2194 if (IsLE && IsVecInReg && DemandedElts == 1 && 2195 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2196 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2197 2198 APInt InDemandedBits = DemandedBits.trunc(InBits); 2199 APInt InDemandedElts = DemandedElts.zext(InElts); 2200 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2201 Depth + 1)) 2202 return true; 2203 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2204 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2205 Known = Known.anyext(BitWidth); 2206 2207 // Attempt to avoid multi-use ops if we don't need anything from them. 2208 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2209 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2210 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2211 break; 2212 } 2213 case ISD::TRUNCATE: { 2214 SDValue Src = Op.getOperand(0); 2215 2216 // Simplify the input, using demanded bit information, and compute the known 2217 // zero/one bits live out. 2218 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2219 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2220 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2221 Depth + 1)) 2222 return true; 2223 Known = Known.trunc(BitWidth); 2224 2225 // Attempt to avoid multi-use ops if we don't need anything from them. 2226 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2227 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2228 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2229 2230 // If the input is only used by this truncate, see if we can shrink it based 2231 // on the known demanded bits. 2232 if (Src.getNode()->hasOneUse()) { 2233 switch (Src.getOpcode()) { 2234 default: 2235 break; 2236 case ISD::SRL: 2237 // Shrink SRL by a constant if none of the high bits shifted in are 2238 // demanded. 2239 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2240 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2241 // undesirable. 2242 break; 2243 2244 const APInt *ShAmtC = 2245 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2246 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2247 break; 2248 uint64_t ShVal = ShAmtC->getZExtValue(); 2249 2250 APInt HighBits = 2251 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2252 HighBits.lshrInPlace(ShVal); 2253 HighBits = HighBits.trunc(BitWidth); 2254 2255 if (!(HighBits & DemandedBits)) { 2256 // None of the shifted in bits are needed. Add a truncate of the 2257 // shift input, then shift it. 2258 SDValue NewShAmt = TLO.DAG.getConstant( 2259 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2260 SDValue NewTrunc = 2261 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2262 return TLO.CombineTo( 2263 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2264 } 2265 break; 2266 } 2267 } 2268 2269 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2270 break; 2271 } 2272 case ISD::AssertZext: { 2273 // AssertZext demands all of the high bits, plus any of the low bits 2274 // demanded by its users. 2275 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2276 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2277 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2278 TLO, Depth + 1)) 2279 return true; 2280 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2281 2282 Known.Zero |= ~InMask; 2283 break; 2284 } 2285 case ISD::EXTRACT_VECTOR_ELT: { 2286 SDValue Src = Op.getOperand(0); 2287 SDValue Idx = Op.getOperand(1); 2288 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2289 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2290 2291 if (SrcEltCnt.isScalable()) 2292 return false; 2293 2294 // Demand the bits from every vector element without a constant index. 2295 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2296 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2297 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2298 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2299 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2300 2301 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2302 // anything about the extended bits. 2303 APInt DemandedSrcBits = DemandedBits; 2304 if (BitWidth > EltBitWidth) 2305 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2306 2307 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2308 Depth + 1)) 2309 return true; 2310 2311 // Attempt to avoid multi-use ops if we don't need anything from them. 2312 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2313 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2314 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2315 SDValue NewOp = 2316 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2317 return TLO.CombineTo(Op, NewOp); 2318 } 2319 } 2320 2321 Known = Known2; 2322 if (BitWidth > EltBitWidth) 2323 Known = Known.anyext(BitWidth); 2324 break; 2325 } 2326 case ISD::BITCAST: { 2327 SDValue Src = Op.getOperand(0); 2328 EVT SrcVT = Src.getValueType(); 2329 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2330 2331 // If this is an FP->Int bitcast and if the sign bit is the only 2332 // thing demanded, turn this into a FGETSIGN. 2333 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2334 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2335 SrcVT.isFloatingPoint()) { 2336 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2337 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2338 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2339 SrcVT != MVT::f128) { 2340 // Cannot eliminate/lower SHL for f128 yet. 2341 EVT Ty = OpVTLegal ? VT : MVT::i32; 2342 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2343 // place. We expect the SHL to be eliminated by other optimizations. 2344 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2345 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2346 if (!OpVTLegal && OpVTSizeInBits > 32) 2347 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2348 unsigned ShVal = Op.getValueSizeInBits() - 1; 2349 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2350 return TLO.CombineTo(Op, 2351 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2352 } 2353 } 2354 2355 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2356 // Demand the elt/bit if any of the original elts/bits are demanded. 2357 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2358 unsigned Scale = BitWidth / NumSrcEltBits; 2359 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2360 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2361 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2362 for (unsigned i = 0; i != Scale; ++i) { 2363 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2364 unsigned BitOffset = EltOffset * NumSrcEltBits; 2365 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2366 if (!Sub.isZero()) { 2367 DemandedSrcBits |= Sub; 2368 for (unsigned j = 0; j != NumElts; ++j) 2369 if (DemandedElts[j]) 2370 DemandedSrcElts.setBit((j * Scale) + i); 2371 } 2372 } 2373 2374 APInt KnownSrcUndef, KnownSrcZero; 2375 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2376 KnownSrcZero, TLO, Depth + 1)) 2377 return true; 2378 2379 KnownBits KnownSrcBits; 2380 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2381 KnownSrcBits, TLO, Depth + 1)) 2382 return true; 2383 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2384 // TODO - bigendian once we have test coverage. 2385 unsigned Scale = NumSrcEltBits / BitWidth; 2386 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2387 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2388 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2389 for (unsigned i = 0; i != NumElts; ++i) 2390 if (DemandedElts[i]) { 2391 unsigned Offset = (i % Scale) * BitWidth; 2392 DemandedSrcBits.insertBits(DemandedBits, Offset); 2393 DemandedSrcElts.setBit(i / Scale); 2394 } 2395 2396 if (SrcVT.isVector()) { 2397 APInt KnownSrcUndef, KnownSrcZero; 2398 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2399 KnownSrcZero, TLO, Depth + 1)) 2400 return true; 2401 } 2402 2403 KnownBits KnownSrcBits; 2404 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2405 KnownSrcBits, TLO, Depth + 1)) 2406 return true; 2407 } 2408 2409 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2410 // recursive call where Known may be useful to the caller. 2411 if (Depth > 0) { 2412 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2413 return false; 2414 } 2415 break; 2416 } 2417 case ISD::MUL: 2418 if (DemandedBits.isPowerOf2()) { 2419 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2420 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2421 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2422 unsigned CTZ = DemandedBits.countTrailingZeros(); 2423 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2424 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2425 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2426 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2427 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2428 return TLO.CombineTo(Op, Shl); 2429 } 2430 } 2431 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2432 // X * X is odd iff X is odd. 2433 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2434 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2435 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2436 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2437 return TLO.CombineTo(Op, And1); 2438 } 2439 LLVM_FALLTHROUGH; 2440 case ISD::ADD: 2441 case ISD::SUB: { 2442 // Add, Sub, and Mul don't demand any bits in positions beyond that 2443 // of the highest bit demanded of them. 2444 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2445 SDNodeFlags Flags = Op.getNode()->getFlags(); 2446 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2447 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2448 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2449 Depth + 1) || 2450 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2451 Depth + 1) || 2452 // See if the operation should be performed at a smaller bit width. 2453 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2454 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2455 // Disable the nsw and nuw flags. We can no longer guarantee that we 2456 // won't wrap after simplification. 2457 Flags.setNoSignedWrap(false); 2458 Flags.setNoUnsignedWrap(false); 2459 SDValue NewOp = 2460 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2461 return TLO.CombineTo(Op, NewOp); 2462 } 2463 return true; 2464 } 2465 2466 // Attempt to avoid multi-use ops if we don't need anything from them. 2467 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2468 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2469 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2470 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2471 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2472 if (DemandedOp0 || DemandedOp1) { 2473 Flags.setNoSignedWrap(false); 2474 Flags.setNoUnsignedWrap(false); 2475 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2476 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2477 SDValue NewOp = 2478 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2479 return TLO.CombineTo(Op, NewOp); 2480 } 2481 } 2482 2483 // If we have a constant operand, we may be able to turn it into -1 if we 2484 // do not demand the high bits. This can make the constant smaller to 2485 // encode, allow more general folding, or match specialized instruction 2486 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2487 // is probably not useful (and could be detrimental). 2488 ConstantSDNode *C = isConstOrConstSplat(Op1); 2489 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2490 if (C && !C->isAllOnes() && !C->isOne() && 2491 (C->getAPIntValue() | HighMask).isAllOnes()) { 2492 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2493 // Disable the nsw and nuw flags. We can no longer guarantee that we 2494 // won't wrap after simplification. 2495 Flags.setNoSignedWrap(false); 2496 Flags.setNoUnsignedWrap(false); 2497 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2498 return TLO.CombineTo(Op, NewOp); 2499 } 2500 2501 // Match a multiply with a disguised negated-power-of-2 and convert to a 2502 // an equivalent shift-left amount. 2503 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2504 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2505 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2506 return 0; 2507 2508 // Don't touch opaque constants. Also, ignore zero and power-of-2 2509 // multiplies. Those will get folded later. 2510 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2511 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2512 !MulC->getAPIntValue().isPowerOf2()) { 2513 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2514 if (UnmaskedC.isNegatedPowerOf2()) 2515 return (-UnmaskedC).logBase2(); 2516 } 2517 return 0; 2518 }; 2519 2520 auto foldMul = [&](SDValue X, SDValue Y, unsigned ShlAmt) { 2521 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2522 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2523 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2524 SDValue Sub = TLO.DAG.getNode(ISD::SUB, dl, VT, Y, Shl); 2525 return TLO.CombineTo(Op, Sub); 2526 }; 2527 2528 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2529 if (Op.getOpcode() == ISD::ADD) { 2530 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2531 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2532 return foldMul(Op0.getOperand(0), Op1, ShAmt); 2533 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2534 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2535 return foldMul(Op1.getOperand(0), Op0, ShAmt); 2536 // TODO: 2537 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2538 } 2539 } 2540 2541 LLVM_FALLTHROUGH; 2542 } 2543 default: 2544 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2545 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2546 Known, TLO, Depth)) 2547 return true; 2548 break; 2549 } 2550 2551 // Just use computeKnownBits to compute output bits. 2552 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2553 break; 2554 } 2555 2556 // If we know the value of all of the demanded bits, return this as a 2557 // constant. 2558 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2559 // Avoid folding to a constant if any OpaqueConstant is involved. 2560 const SDNode *N = Op.getNode(); 2561 for (SDNode *Op : 2562 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2563 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2564 if (C->isOpaque()) 2565 return false; 2566 } 2567 if (VT.isInteger()) 2568 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2569 if (VT.isFloatingPoint()) 2570 return TLO.CombineTo( 2571 Op, 2572 TLO.DAG.getConstantFP( 2573 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2574 } 2575 2576 return false; 2577 } 2578 2579 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2580 const APInt &DemandedElts, 2581 DAGCombinerInfo &DCI) const { 2582 SelectionDAG &DAG = DCI.DAG; 2583 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2584 !DCI.isBeforeLegalizeOps()); 2585 2586 APInt KnownUndef, KnownZero; 2587 bool Simplified = 2588 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2589 if (Simplified) { 2590 DCI.AddToWorklist(Op.getNode()); 2591 DCI.CommitTargetLoweringOpt(TLO); 2592 } 2593 2594 return Simplified; 2595 } 2596 2597 /// Given a vector binary operation and known undefined elements for each input 2598 /// operand, compute whether each element of the output is undefined. 2599 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2600 const APInt &UndefOp0, 2601 const APInt &UndefOp1) { 2602 EVT VT = BO.getValueType(); 2603 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2604 "Vector binop only"); 2605 2606 EVT EltVT = VT.getVectorElementType(); 2607 unsigned NumElts = VT.getVectorNumElements(); 2608 assert(UndefOp0.getBitWidth() == NumElts && 2609 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2610 2611 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2612 const APInt &UndefVals) { 2613 if (UndefVals[Index]) 2614 return DAG.getUNDEF(EltVT); 2615 2616 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2617 // Try hard to make sure that the getNode() call is not creating temporary 2618 // nodes. Ignore opaque integers because they do not constant fold. 2619 SDValue Elt = BV->getOperand(Index); 2620 auto *C = dyn_cast<ConstantSDNode>(Elt); 2621 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2622 return Elt; 2623 } 2624 2625 return SDValue(); 2626 }; 2627 2628 APInt KnownUndef = APInt::getZero(NumElts); 2629 for (unsigned i = 0; i != NumElts; ++i) { 2630 // If both inputs for this element are either constant or undef and match 2631 // the element type, compute the constant/undef result for this element of 2632 // the vector. 2633 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2634 // not handle FP constants. The code within getNode() should be refactored 2635 // to avoid the danger of creating a bogus temporary node here. 2636 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2637 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2638 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2639 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2640 KnownUndef.setBit(i); 2641 } 2642 return KnownUndef; 2643 } 2644 2645 bool TargetLowering::SimplifyDemandedVectorElts( 2646 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2647 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2648 bool AssumeSingleUse) const { 2649 EVT VT = Op.getValueType(); 2650 unsigned Opcode = Op.getOpcode(); 2651 APInt DemandedElts = OriginalDemandedElts; 2652 unsigned NumElts = DemandedElts.getBitWidth(); 2653 assert(VT.isVector() && "Expected vector op"); 2654 2655 KnownUndef = KnownZero = APInt::getZero(NumElts); 2656 2657 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2658 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2659 return false; 2660 2661 // TODO: For now we assume we know nothing about scalable vectors. 2662 if (VT.isScalableVector()) 2663 return false; 2664 2665 assert(VT.getVectorNumElements() == NumElts && 2666 "Mask size mismatches value type element count!"); 2667 2668 // Undef operand. 2669 if (Op.isUndef()) { 2670 KnownUndef.setAllBits(); 2671 return false; 2672 } 2673 2674 // If Op has other users, assume that all elements are needed. 2675 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2676 DemandedElts.setAllBits(); 2677 2678 // Not demanding any elements from Op. 2679 if (DemandedElts == 0) { 2680 KnownUndef.setAllBits(); 2681 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2682 } 2683 2684 // Limit search depth. 2685 if (Depth >= SelectionDAG::MaxRecursionDepth) 2686 return false; 2687 2688 SDLoc DL(Op); 2689 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2690 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2691 2692 // Helper for demanding the specified elements and all the bits of both binary 2693 // operands. 2694 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2695 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2696 TLO.DAG, Depth + 1); 2697 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2698 TLO.DAG, Depth + 1); 2699 if (NewOp0 || NewOp1) { 2700 SDValue NewOp = TLO.DAG.getNode( 2701 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2702 return TLO.CombineTo(Op, NewOp); 2703 } 2704 return false; 2705 }; 2706 2707 switch (Opcode) { 2708 case ISD::SCALAR_TO_VECTOR: { 2709 if (!DemandedElts[0]) { 2710 KnownUndef.setAllBits(); 2711 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2712 } 2713 SDValue ScalarSrc = Op.getOperand(0); 2714 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2715 SDValue Src = ScalarSrc.getOperand(0); 2716 SDValue Idx = ScalarSrc.getOperand(1); 2717 EVT SrcVT = Src.getValueType(); 2718 2719 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2720 2721 if (SrcEltCnt.isScalable()) 2722 return false; 2723 2724 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2725 if (isNullConstant(Idx)) { 2726 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2727 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2728 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2729 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2730 TLO, Depth + 1)) 2731 return true; 2732 } 2733 } 2734 KnownUndef.setHighBits(NumElts - 1); 2735 break; 2736 } 2737 case ISD::BITCAST: { 2738 SDValue Src = Op.getOperand(0); 2739 EVT SrcVT = Src.getValueType(); 2740 2741 // We only handle vectors here. 2742 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2743 if (!SrcVT.isVector()) 2744 break; 2745 2746 // Fast handling of 'identity' bitcasts. 2747 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2748 if (NumSrcElts == NumElts) 2749 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2750 KnownZero, TLO, Depth + 1); 2751 2752 APInt SrcDemandedElts, SrcZero, SrcUndef; 2753 2754 // Bitcast from 'large element' src vector to 'small element' vector, we 2755 // must demand a source element if any DemandedElt maps to it. 2756 if ((NumElts % NumSrcElts) == 0) { 2757 unsigned Scale = NumElts / NumSrcElts; 2758 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2759 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2760 TLO, Depth + 1)) 2761 return true; 2762 2763 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2764 // of the large element. 2765 // TODO - bigendian once we have test coverage. 2766 if (IsLE) { 2767 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2768 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2769 for (unsigned i = 0; i != NumElts; ++i) 2770 if (DemandedElts[i]) { 2771 unsigned Ofs = (i % Scale) * EltSizeInBits; 2772 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2773 } 2774 2775 KnownBits Known; 2776 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2777 TLO, Depth + 1)) 2778 return true; 2779 2780 // The bitcast has split each wide element into a number of 2781 // narrow subelements. We have just computed the Known bits 2782 // for wide elements. See if element splitting results in 2783 // some subelements being zero. Only for demanded elements! 2784 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2785 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2786 .isAllOnes()) 2787 continue; 2788 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2789 unsigned Elt = Scale * SrcElt + SubElt; 2790 if (DemandedElts[Elt]) 2791 KnownZero.setBit(Elt); 2792 } 2793 } 2794 } 2795 2796 // If the src element is zero/undef then all the output elements will be - 2797 // only demanded elements are guaranteed to be correct. 2798 for (unsigned i = 0; i != NumSrcElts; ++i) { 2799 if (SrcDemandedElts[i]) { 2800 if (SrcZero[i]) 2801 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2802 if (SrcUndef[i]) 2803 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2804 } 2805 } 2806 } 2807 2808 // Bitcast from 'small element' src vector to 'large element' vector, we 2809 // demand all smaller source elements covered by the larger demanded element 2810 // of this vector. 2811 if ((NumSrcElts % NumElts) == 0) { 2812 unsigned Scale = NumSrcElts / NumElts; 2813 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2814 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2815 TLO, Depth + 1)) 2816 return true; 2817 2818 // If all the src elements covering an output element are zero/undef, then 2819 // the output element will be as well, assuming it was demanded. 2820 for (unsigned i = 0; i != NumElts; ++i) { 2821 if (DemandedElts[i]) { 2822 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2823 KnownZero.setBit(i); 2824 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2825 KnownUndef.setBit(i); 2826 } 2827 } 2828 } 2829 break; 2830 } 2831 case ISD::BUILD_VECTOR: { 2832 // Check all elements and simplify any unused elements with UNDEF. 2833 if (!DemandedElts.isAllOnes()) { 2834 // Don't simplify BROADCASTS. 2835 if (llvm::any_of(Op->op_values(), 2836 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2837 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2838 bool Updated = false; 2839 for (unsigned i = 0; i != NumElts; ++i) { 2840 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2841 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2842 KnownUndef.setBit(i); 2843 Updated = true; 2844 } 2845 } 2846 if (Updated) 2847 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2848 } 2849 } 2850 for (unsigned i = 0; i != NumElts; ++i) { 2851 SDValue SrcOp = Op.getOperand(i); 2852 if (SrcOp.isUndef()) { 2853 KnownUndef.setBit(i); 2854 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2855 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2856 KnownZero.setBit(i); 2857 } 2858 } 2859 break; 2860 } 2861 case ISD::CONCAT_VECTORS: { 2862 EVT SubVT = Op.getOperand(0).getValueType(); 2863 unsigned NumSubVecs = Op.getNumOperands(); 2864 unsigned NumSubElts = SubVT.getVectorNumElements(); 2865 for (unsigned i = 0; i != NumSubVecs; ++i) { 2866 SDValue SubOp = Op.getOperand(i); 2867 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2868 APInt SubUndef, SubZero; 2869 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2870 Depth + 1)) 2871 return true; 2872 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2873 KnownZero.insertBits(SubZero, i * NumSubElts); 2874 } 2875 2876 // Attempt to avoid multi-use ops if we don't need anything from them. 2877 if (!DemandedElts.isAllOnes()) { 2878 bool FoundNewSub = false; 2879 SmallVector<SDValue, 2> DemandedSubOps; 2880 for (unsigned i = 0; i != NumSubVecs; ++i) { 2881 SDValue SubOp = Op.getOperand(i); 2882 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2883 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 2884 SubOp, SubElts, TLO.DAG, Depth + 1); 2885 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 2886 FoundNewSub = NewSubOp ? true : FoundNewSub; 2887 } 2888 if (FoundNewSub) { 2889 SDValue NewOp = 2890 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 2891 return TLO.CombineTo(Op, NewOp); 2892 } 2893 } 2894 break; 2895 } 2896 case ISD::INSERT_SUBVECTOR: { 2897 // Demand any elements from the subvector and the remainder from the src its 2898 // inserted into. 2899 SDValue Src = Op.getOperand(0); 2900 SDValue Sub = Op.getOperand(1); 2901 uint64_t Idx = Op.getConstantOperandVal(2); 2902 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2903 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2904 APInt DemandedSrcElts = DemandedElts; 2905 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2906 2907 APInt SubUndef, SubZero; 2908 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2909 Depth + 1)) 2910 return true; 2911 2912 // If none of the src operand elements are demanded, replace it with undef. 2913 if (!DemandedSrcElts && !Src.isUndef()) 2914 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2915 TLO.DAG.getUNDEF(VT), Sub, 2916 Op.getOperand(2))); 2917 2918 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2919 TLO, Depth + 1)) 2920 return true; 2921 KnownUndef.insertBits(SubUndef, Idx); 2922 KnownZero.insertBits(SubZero, Idx); 2923 2924 // Attempt to avoid multi-use ops if we don't need anything from them. 2925 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 2926 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2927 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2928 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2929 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2930 if (NewSrc || NewSub) { 2931 NewSrc = NewSrc ? NewSrc : Src; 2932 NewSub = NewSub ? NewSub : Sub; 2933 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2934 NewSub, Op.getOperand(2)); 2935 return TLO.CombineTo(Op, NewOp); 2936 } 2937 } 2938 break; 2939 } 2940 case ISD::EXTRACT_SUBVECTOR: { 2941 // Offset the demanded elts by the subvector index. 2942 SDValue Src = Op.getOperand(0); 2943 if (Src.getValueType().isScalableVector()) 2944 break; 2945 uint64_t Idx = Op.getConstantOperandVal(1); 2946 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2947 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2948 2949 APInt SrcUndef, SrcZero; 2950 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2951 Depth + 1)) 2952 return true; 2953 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2954 KnownZero = SrcZero.extractBits(NumElts, Idx); 2955 2956 // Attempt to avoid multi-use ops if we don't need anything from them. 2957 if (!DemandedElts.isAllOnes()) { 2958 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2959 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2960 if (NewSrc) { 2961 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2962 Op.getOperand(1)); 2963 return TLO.CombineTo(Op, NewOp); 2964 } 2965 } 2966 break; 2967 } 2968 case ISD::INSERT_VECTOR_ELT: { 2969 SDValue Vec = Op.getOperand(0); 2970 SDValue Scl = Op.getOperand(1); 2971 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2972 2973 // For a legal, constant insertion index, if we don't need this insertion 2974 // then strip it, else remove it from the demanded elts. 2975 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2976 unsigned Idx = CIdx->getZExtValue(); 2977 if (!DemandedElts[Idx]) 2978 return TLO.CombineTo(Op, Vec); 2979 2980 APInt DemandedVecElts(DemandedElts); 2981 DemandedVecElts.clearBit(Idx); 2982 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2983 KnownZero, TLO, Depth + 1)) 2984 return true; 2985 2986 KnownUndef.setBitVal(Idx, Scl.isUndef()); 2987 2988 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 2989 break; 2990 } 2991 2992 APInt VecUndef, VecZero; 2993 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2994 Depth + 1)) 2995 return true; 2996 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2997 break; 2998 } 2999 case ISD::VSELECT: { 3000 // Try to transform the select condition based on the current demanded 3001 // elements. 3002 // TODO: If a condition element is undef, we can choose from one arm of the 3003 // select (and if one arm is undef, then we can propagate that to the 3004 // result). 3005 // TODO - add support for constant vselect masks (see IR version of this). 3006 APInt UnusedUndef, UnusedZero; 3007 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 3008 UnusedZero, TLO, Depth + 1)) 3009 return true; 3010 3011 // See if we can simplify either vselect operand. 3012 APInt DemandedLHS(DemandedElts); 3013 APInt DemandedRHS(DemandedElts); 3014 APInt UndefLHS, ZeroLHS; 3015 APInt UndefRHS, ZeroRHS; 3016 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 3017 ZeroLHS, TLO, Depth + 1)) 3018 return true; 3019 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 3020 ZeroRHS, TLO, Depth + 1)) 3021 return true; 3022 3023 KnownUndef = UndefLHS & UndefRHS; 3024 KnownZero = ZeroLHS & ZeroRHS; 3025 break; 3026 } 3027 case ISD::VECTOR_SHUFFLE: { 3028 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3029 3030 // Collect demanded elements from shuffle operands.. 3031 APInt DemandedLHS(NumElts, 0); 3032 APInt DemandedRHS(NumElts, 0); 3033 for (unsigned i = 0; i != NumElts; ++i) { 3034 int M = ShuffleMask[i]; 3035 if (M < 0 || !DemandedElts[i]) 3036 continue; 3037 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3038 if (M < (int)NumElts) 3039 DemandedLHS.setBit(M); 3040 else 3041 DemandedRHS.setBit(M - NumElts); 3042 } 3043 3044 // See if we can simplify either shuffle operand. 3045 APInt UndefLHS, ZeroLHS; 3046 APInt UndefRHS, ZeroRHS; 3047 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3048 ZeroLHS, TLO, Depth + 1)) 3049 return true; 3050 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3051 ZeroRHS, TLO, Depth + 1)) 3052 return true; 3053 3054 // Simplify mask using undef elements from LHS/RHS. 3055 bool Updated = false; 3056 bool IdentityLHS = true, IdentityRHS = true; 3057 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3058 for (unsigned i = 0; i != NumElts; ++i) { 3059 int &M = NewMask[i]; 3060 if (M < 0) 3061 continue; 3062 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3063 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3064 Updated = true; 3065 M = -1; 3066 } 3067 IdentityLHS &= (M < 0) || (M == (int)i); 3068 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3069 } 3070 3071 // Update legal shuffle masks based on demanded elements if it won't reduce 3072 // to Identity which can cause premature removal of the shuffle mask. 3073 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3074 SDValue LegalShuffle = 3075 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3076 NewMask, TLO.DAG); 3077 if (LegalShuffle) 3078 return TLO.CombineTo(Op, LegalShuffle); 3079 } 3080 3081 // Propagate undef/zero elements from LHS/RHS. 3082 for (unsigned i = 0; i != NumElts; ++i) { 3083 int M = ShuffleMask[i]; 3084 if (M < 0) { 3085 KnownUndef.setBit(i); 3086 } else if (M < (int)NumElts) { 3087 if (UndefLHS[M]) 3088 KnownUndef.setBit(i); 3089 if (ZeroLHS[M]) 3090 KnownZero.setBit(i); 3091 } else { 3092 if (UndefRHS[M - NumElts]) 3093 KnownUndef.setBit(i); 3094 if (ZeroRHS[M - NumElts]) 3095 KnownZero.setBit(i); 3096 } 3097 } 3098 break; 3099 } 3100 case ISD::ANY_EXTEND_VECTOR_INREG: 3101 case ISD::SIGN_EXTEND_VECTOR_INREG: 3102 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3103 APInt SrcUndef, SrcZero; 3104 SDValue Src = Op.getOperand(0); 3105 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3106 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3107 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3108 Depth + 1)) 3109 return true; 3110 KnownZero = SrcZero.zextOrTrunc(NumElts); 3111 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3112 3113 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3114 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3115 DemandedSrcElts == 1) { 3116 // aext - if we just need the bottom element then we can bitcast. 3117 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3118 } 3119 3120 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3121 // zext(undef) upper bits are guaranteed to be zero. 3122 if (DemandedElts.isSubsetOf(KnownUndef)) 3123 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3124 KnownUndef.clearAllBits(); 3125 3126 // zext - if we just need the bottom element then we can mask: 3127 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3128 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3129 Op->isOnlyUserOf(Src.getNode()) && 3130 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3131 SDLoc DL(Op); 3132 EVT SrcVT = Src.getValueType(); 3133 EVT SrcSVT = SrcVT.getScalarType(); 3134 SmallVector<SDValue> MaskElts; 3135 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3136 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3137 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3138 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3139 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3140 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3141 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3142 } 3143 } 3144 } 3145 break; 3146 } 3147 3148 // TODO: There are more binop opcodes that could be handled here - MIN, 3149 // MAX, saturated math, etc. 3150 case ISD::ADD: { 3151 SDValue Op0 = Op.getOperand(0); 3152 SDValue Op1 = Op.getOperand(1); 3153 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3154 APInt UndefLHS, ZeroLHS; 3155 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3156 Depth + 1, /*AssumeSingleUse*/ true)) 3157 return true; 3158 } 3159 LLVM_FALLTHROUGH; 3160 } 3161 case ISD::OR: 3162 case ISD::XOR: 3163 case ISD::SUB: 3164 case ISD::FADD: 3165 case ISD::FSUB: 3166 case ISD::FMUL: 3167 case ISD::FDIV: 3168 case ISD::FREM: { 3169 SDValue Op0 = Op.getOperand(0); 3170 SDValue Op1 = Op.getOperand(1); 3171 3172 APInt UndefRHS, ZeroRHS; 3173 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3174 Depth + 1)) 3175 return true; 3176 APInt UndefLHS, ZeroLHS; 3177 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3178 Depth + 1)) 3179 return true; 3180 3181 KnownZero = ZeroLHS & ZeroRHS; 3182 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3183 3184 // Attempt to avoid multi-use ops if we don't need anything from them. 3185 // TODO - use KnownUndef to relax the demandedelts? 3186 if (!DemandedElts.isAllOnes()) 3187 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3188 return true; 3189 break; 3190 } 3191 case ISD::SHL: 3192 case ISD::SRL: 3193 case ISD::SRA: 3194 case ISD::ROTL: 3195 case ISD::ROTR: { 3196 SDValue Op0 = Op.getOperand(0); 3197 SDValue Op1 = Op.getOperand(1); 3198 3199 APInt UndefRHS, ZeroRHS; 3200 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3201 Depth + 1)) 3202 return true; 3203 APInt UndefLHS, ZeroLHS; 3204 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3205 Depth + 1)) 3206 return true; 3207 3208 KnownZero = ZeroLHS; 3209 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3210 3211 // Attempt to avoid multi-use ops if we don't need anything from them. 3212 // TODO - use KnownUndef to relax the demandedelts? 3213 if (!DemandedElts.isAllOnes()) 3214 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3215 return true; 3216 break; 3217 } 3218 case ISD::MUL: 3219 case ISD::AND: { 3220 SDValue Op0 = Op.getOperand(0); 3221 SDValue Op1 = Op.getOperand(1); 3222 3223 APInt SrcUndef, SrcZero; 3224 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3225 Depth + 1)) 3226 return true; 3227 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3228 TLO, Depth + 1)) 3229 return true; 3230 3231 // If either side has a zero element, then the result element is zero, even 3232 // if the other is an UNDEF. 3233 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3234 // and then handle 'and' nodes with the rest of the binop opcodes. 3235 KnownZero |= SrcZero; 3236 KnownUndef &= SrcUndef; 3237 KnownUndef &= ~KnownZero; 3238 3239 // Attempt to avoid multi-use ops if we don't need anything from them. 3240 // TODO - use KnownUndef to relax the demandedelts? 3241 if (!DemandedElts.isAllOnes()) 3242 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3243 return true; 3244 break; 3245 } 3246 case ISD::TRUNCATE: 3247 case ISD::SIGN_EXTEND: 3248 case ISD::ZERO_EXTEND: 3249 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3250 KnownZero, TLO, Depth + 1)) 3251 return true; 3252 3253 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3254 // zext(undef) upper bits are guaranteed to be zero. 3255 if (DemandedElts.isSubsetOf(KnownUndef)) 3256 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3257 KnownUndef.clearAllBits(); 3258 } 3259 break; 3260 default: { 3261 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3262 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3263 KnownZero, TLO, Depth)) 3264 return true; 3265 } else { 3266 KnownBits Known; 3267 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3268 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3269 TLO, Depth, AssumeSingleUse)) 3270 return true; 3271 } 3272 break; 3273 } 3274 } 3275 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3276 3277 // Constant fold all undef cases. 3278 // TODO: Handle zero cases as well. 3279 if (DemandedElts.isSubsetOf(KnownUndef)) 3280 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3281 3282 return false; 3283 } 3284 3285 /// Determine which of the bits specified in Mask are known to be either zero or 3286 /// one and return them in the Known. 3287 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3288 KnownBits &Known, 3289 const APInt &DemandedElts, 3290 const SelectionDAG &DAG, 3291 unsigned Depth) const { 3292 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3293 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3294 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3295 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3296 "Should use MaskedValueIsZero if you don't know whether Op" 3297 " is a target node!"); 3298 Known.resetAll(); 3299 } 3300 3301 void TargetLowering::computeKnownBitsForTargetInstr( 3302 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3303 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3304 unsigned Depth) const { 3305 Known.resetAll(); 3306 } 3307 3308 void TargetLowering::computeKnownBitsForFrameIndex( 3309 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3310 // The low bits are known zero if the pointer is aligned. 3311 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3312 } 3313 3314 Align TargetLowering::computeKnownAlignForTargetInstr( 3315 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3316 unsigned Depth) const { 3317 return Align(1); 3318 } 3319 3320 /// This method can be implemented by targets that want to expose additional 3321 /// information about sign bits to the DAG Combiner. 3322 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3323 const APInt &, 3324 const SelectionDAG &, 3325 unsigned Depth) const { 3326 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3327 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3328 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3329 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3330 "Should use ComputeNumSignBits if you don't know whether Op" 3331 " is a target node!"); 3332 return 1; 3333 } 3334 3335 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3336 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3337 const MachineRegisterInfo &MRI, unsigned Depth) const { 3338 return 1; 3339 } 3340 3341 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3342 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3343 TargetLoweringOpt &TLO, unsigned Depth) const { 3344 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3345 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3346 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3347 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3348 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3349 " is a target node!"); 3350 return false; 3351 } 3352 3353 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3354 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3355 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3356 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3357 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3358 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3359 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3360 "Should use SimplifyDemandedBits if you don't know whether Op" 3361 " is a target node!"); 3362 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3363 return false; 3364 } 3365 3366 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3367 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3368 SelectionDAG &DAG, unsigned Depth) const { 3369 assert( 3370 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3371 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3372 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3373 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3374 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3375 " is a target node!"); 3376 return SDValue(); 3377 } 3378 3379 SDValue 3380 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3381 SDValue N1, MutableArrayRef<int> Mask, 3382 SelectionDAG &DAG) const { 3383 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3384 if (!LegalMask) { 3385 std::swap(N0, N1); 3386 ShuffleVectorSDNode::commuteMask(Mask); 3387 LegalMask = isShuffleMaskLegal(Mask, VT); 3388 } 3389 3390 if (!LegalMask) 3391 return SDValue(); 3392 3393 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3394 } 3395 3396 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3397 return nullptr; 3398 } 3399 3400 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3401 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3402 bool PoisonOnly, unsigned Depth) const { 3403 assert( 3404 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3405 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3406 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3407 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3408 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3409 " is a target node!"); 3410 return false; 3411 } 3412 3413 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3414 const SelectionDAG &DAG, 3415 bool SNaN, 3416 unsigned Depth) const { 3417 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3418 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3419 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3420 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3421 "Should use isKnownNeverNaN if you don't know whether Op" 3422 " is a target node!"); 3423 return false; 3424 } 3425 3426 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3427 const APInt &DemandedElts, 3428 APInt &UndefElts, 3429 unsigned Depth) const { 3430 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3431 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3432 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3433 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3434 "Should use isSplatValue if you don't know whether Op" 3435 " is a target node!"); 3436 return false; 3437 } 3438 3439 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3440 // work with truncating build vectors and vectors with elements of less than 3441 // 8 bits. 3442 bool TargetLowering::isConstTrueVal(SDValue N) const { 3443 if (!N) 3444 return false; 3445 3446 unsigned EltWidth; 3447 APInt CVal; 3448 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3449 /*AllowTruncation=*/true)) { 3450 CVal = CN->getAPIntValue(); 3451 EltWidth = N.getValueType().getScalarSizeInBits(); 3452 } else 3453 return false; 3454 3455 // If this is a truncating splat, truncate the splat value. 3456 // Otherwise, we may fail to match the expected values below. 3457 if (EltWidth < CVal.getBitWidth()) 3458 CVal = CVal.trunc(EltWidth); 3459 3460 switch (getBooleanContents(N.getValueType())) { 3461 case UndefinedBooleanContent: 3462 return CVal[0]; 3463 case ZeroOrOneBooleanContent: 3464 return CVal.isOne(); 3465 case ZeroOrNegativeOneBooleanContent: 3466 return CVal.isAllOnes(); 3467 } 3468 3469 llvm_unreachable("Invalid boolean contents"); 3470 } 3471 3472 bool TargetLowering::isConstFalseVal(SDValue N) const { 3473 if (!N) 3474 return false; 3475 3476 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3477 if (!CN) { 3478 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3479 if (!BV) 3480 return false; 3481 3482 // Only interested in constant splats, we don't care about undef 3483 // elements in identifying boolean constants and getConstantSplatNode 3484 // returns NULL if all ops are undef; 3485 CN = BV->getConstantSplatNode(); 3486 if (!CN) 3487 return false; 3488 } 3489 3490 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3491 return !CN->getAPIntValue()[0]; 3492 3493 return CN->isZero(); 3494 } 3495 3496 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3497 bool SExt) const { 3498 if (VT == MVT::i1) 3499 return N->isOne(); 3500 3501 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3502 switch (Cnt) { 3503 case TargetLowering::ZeroOrOneBooleanContent: 3504 // An extended value of 1 is always true, unless its original type is i1, 3505 // in which case it will be sign extended to -1. 3506 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3507 case TargetLowering::UndefinedBooleanContent: 3508 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3509 return N->isAllOnes() && SExt; 3510 } 3511 llvm_unreachable("Unexpected enumeration."); 3512 } 3513 3514 /// This helper function of SimplifySetCC tries to optimize the comparison when 3515 /// either operand of the SetCC node is a bitwise-and instruction. 3516 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3517 ISD::CondCode Cond, const SDLoc &DL, 3518 DAGCombinerInfo &DCI) const { 3519 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3520 std::swap(N0, N1); 3521 3522 SelectionDAG &DAG = DCI.DAG; 3523 EVT OpVT = N0.getValueType(); 3524 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3525 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3526 return SDValue(); 3527 3528 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3529 // iff everything but LSB is known zero: 3530 if (Cond == ISD::SETNE && isNullConstant(N1) && 3531 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3532 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3533 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3534 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3535 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3536 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3537 } 3538 3539 // Match these patterns in any of their permutations: 3540 // (X & Y) == Y 3541 // (X & Y) != Y 3542 SDValue X, Y; 3543 if (N0.getOperand(0) == N1) { 3544 X = N0.getOperand(1); 3545 Y = N0.getOperand(0); 3546 } else if (N0.getOperand(1) == N1) { 3547 X = N0.getOperand(0); 3548 Y = N0.getOperand(1); 3549 } else { 3550 return SDValue(); 3551 } 3552 3553 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3554 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3555 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3556 // Note that where Y is variable and is known to have at most one bit set 3557 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3558 // equivalent when Y == 0. 3559 assert(OpVT.isInteger()); 3560 Cond = ISD::getSetCCInverse(Cond, OpVT); 3561 if (DCI.isBeforeLegalizeOps() || 3562 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3563 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3564 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3565 // If the target supports an 'and-not' or 'and-complement' logic operation, 3566 // try to use that to make a comparison operation more efficient. 3567 // But don't do this transform if the mask is a single bit because there are 3568 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3569 // 'rlwinm' on PPC). 3570 3571 // Bail out if the compare operand that we want to turn into a zero is 3572 // already a zero (otherwise, infinite loop). 3573 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3574 if (YConst && YConst->isZero()) 3575 return SDValue(); 3576 3577 // Transform this into: ~X & Y == 0. 3578 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3579 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3580 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3581 } 3582 3583 return SDValue(); 3584 } 3585 3586 /// There are multiple IR patterns that could be checking whether certain 3587 /// truncation of a signed number would be lossy or not. The pattern which is 3588 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3589 /// We are looking for the following pattern: (KeptBits is a constant) 3590 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3591 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3592 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3593 /// We will unfold it into the natural trunc+sext pattern: 3594 /// ((%x << C) a>> C) dstcond %x 3595 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3596 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3597 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3598 const SDLoc &DL) const { 3599 // We must be comparing with a constant. 3600 ConstantSDNode *C1; 3601 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3602 return SDValue(); 3603 3604 // N0 should be: add %x, (1 << (KeptBits-1)) 3605 if (N0->getOpcode() != ISD::ADD) 3606 return SDValue(); 3607 3608 // And we must be 'add'ing a constant. 3609 ConstantSDNode *C01; 3610 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3611 return SDValue(); 3612 3613 SDValue X = N0->getOperand(0); 3614 EVT XVT = X.getValueType(); 3615 3616 // Validate constants ... 3617 3618 APInt I1 = C1->getAPIntValue(); 3619 3620 ISD::CondCode NewCond; 3621 if (Cond == ISD::CondCode::SETULT) { 3622 NewCond = ISD::CondCode::SETEQ; 3623 } else if (Cond == ISD::CondCode::SETULE) { 3624 NewCond = ISD::CondCode::SETEQ; 3625 // But need to 'canonicalize' the constant. 3626 I1 += 1; 3627 } else if (Cond == ISD::CondCode::SETUGT) { 3628 NewCond = ISD::CondCode::SETNE; 3629 // But need to 'canonicalize' the constant. 3630 I1 += 1; 3631 } else if (Cond == ISD::CondCode::SETUGE) { 3632 NewCond = ISD::CondCode::SETNE; 3633 } else 3634 return SDValue(); 3635 3636 APInt I01 = C01->getAPIntValue(); 3637 3638 auto checkConstants = [&I1, &I01]() -> bool { 3639 // Both of them must be power-of-two, and the constant from setcc is bigger. 3640 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3641 }; 3642 3643 if (checkConstants()) { 3644 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3645 } else { 3646 // What if we invert constants? (and the target predicate) 3647 I1.negate(); 3648 I01.negate(); 3649 assert(XVT.isInteger()); 3650 NewCond = getSetCCInverse(NewCond, XVT); 3651 if (!checkConstants()) 3652 return SDValue(); 3653 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3654 } 3655 3656 // They are power-of-two, so which bit is set? 3657 const unsigned KeptBits = I1.logBase2(); 3658 const unsigned KeptBitsMinusOne = I01.logBase2(); 3659 3660 // Magic! 3661 if (KeptBits != (KeptBitsMinusOne + 1)) 3662 return SDValue(); 3663 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3664 3665 // We don't want to do this in every single case. 3666 SelectionDAG &DAG = DCI.DAG; 3667 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3668 XVT, KeptBits)) 3669 return SDValue(); 3670 3671 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3672 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3673 3674 // Unfold into: ((%x << C) a>> C) cond %x 3675 // Where 'cond' will be either 'eq' or 'ne'. 3676 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3677 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3678 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3679 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3680 3681 return T2; 3682 } 3683 3684 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3685 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3686 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3687 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3688 assert(isConstOrConstSplat(N1C) && 3689 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3690 "Should be a comparison with 0."); 3691 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3692 "Valid only for [in]equality comparisons."); 3693 3694 unsigned NewShiftOpcode; 3695 SDValue X, C, Y; 3696 3697 SelectionDAG &DAG = DCI.DAG; 3698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3699 3700 // Look for '(C l>>/<< Y)'. 3701 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3702 // The shift should be one-use. 3703 if (!V.hasOneUse()) 3704 return false; 3705 unsigned OldShiftOpcode = V.getOpcode(); 3706 switch (OldShiftOpcode) { 3707 case ISD::SHL: 3708 NewShiftOpcode = ISD::SRL; 3709 break; 3710 case ISD::SRL: 3711 NewShiftOpcode = ISD::SHL; 3712 break; 3713 default: 3714 return false; // must be a logical shift. 3715 } 3716 // We should be shifting a constant. 3717 // FIXME: best to use isConstantOrConstantVector(). 3718 C = V.getOperand(0); 3719 ConstantSDNode *CC = 3720 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3721 if (!CC) 3722 return false; 3723 Y = V.getOperand(1); 3724 3725 ConstantSDNode *XC = 3726 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3727 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3728 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3729 }; 3730 3731 // LHS of comparison should be an one-use 'and'. 3732 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3733 return SDValue(); 3734 3735 X = N0.getOperand(0); 3736 SDValue Mask = N0.getOperand(1); 3737 3738 // 'and' is commutative! 3739 if (!Match(Mask)) { 3740 std::swap(X, Mask); 3741 if (!Match(Mask)) 3742 return SDValue(); 3743 } 3744 3745 EVT VT = X.getValueType(); 3746 3747 // Produce: 3748 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3749 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3750 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3751 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3752 return T2; 3753 } 3754 3755 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3756 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3757 /// handle the commuted versions of these patterns. 3758 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3759 ISD::CondCode Cond, const SDLoc &DL, 3760 DAGCombinerInfo &DCI) const { 3761 unsigned BOpcode = N0.getOpcode(); 3762 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3763 "Unexpected binop"); 3764 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3765 3766 // (X + Y) == X --> Y == 0 3767 // (X - Y) == X --> Y == 0 3768 // (X ^ Y) == X --> Y == 0 3769 SelectionDAG &DAG = DCI.DAG; 3770 EVT OpVT = N0.getValueType(); 3771 SDValue X = N0.getOperand(0); 3772 SDValue Y = N0.getOperand(1); 3773 if (X == N1) 3774 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3775 3776 if (Y != N1) 3777 return SDValue(); 3778 3779 // (X + Y) == Y --> X == 0 3780 // (X ^ Y) == Y --> X == 0 3781 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3782 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3783 3784 // The shift would not be valid if the operands are boolean (i1). 3785 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3786 return SDValue(); 3787 3788 // (X - Y) == Y --> X == Y << 1 3789 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3790 !DCI.isBeforeLegalize()); 3791 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3792 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3793 if (!DCI.isCalledByLegalizer()) 3794 DCI.AddToWorklist(YShl1.getNode()); 3795 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3796 } 3797 3798 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3799 SDValue N0, const APInt &C1, 3800 ISD::CondCode Cond, const SDLoc &dl, 3801 SelectionDAG &DAG) { 3802 // Look through truncs that don't change the value of a ctpop. 3803 // FIXME: Add vector support? Need to be careful with setcc result type below. 3804 SDValue CTPOP = N0; 3805 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3806 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3807 CTPOP = N0.getOperand(0); 3808 3809 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3810 return SDValue(); 3811 3812 EVT CTVT = CTPOP.getValueType(); 3813 SDValue CTOp = CTPOP.getOperand(0); 3814 3815 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3816 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3817 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3818 return SDValue(); 3819 3820 // (ctpop x) u< 2 -> (x & x-1) == 0 3821 // (ctpop x) u> 1 -> (x & x-1) != 0 3822 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3823 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3824 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3825 return SDValue(); 3826 if (C1 == 0 && (Cond == ISD::SETULT)) 3827 return SDValue(); // This is handled elsewhere. 3828 3829 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3830 3831 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3832 SDValue Result = CTOp; 3833 for (unsigned i = 0; i < Passes; i++) { 3834 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3835 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3836 } 3837 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3838 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3839 } 3840 3841 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3842 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3843 // For scalars, keep CTPOP if it is legal or custom. 3844 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3845 return SDValue(); 3846 // This is based on X86's custom lowering for CTPOP which produces more 3847 // instructions than the expansion here. 3848 3849 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3850 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3851 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3852 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3853 assert(CTVT.isInteger()); 3854 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3855 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3856 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3857 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3858 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3859 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3860 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3861 } 3862 3863 return SDValue(); 3864 } 3865 3866 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3867 ISD::CondCode Cond, const SDLoc &dl, 3868 SelectionDAG &DAG) { 3869 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3870 return SDValue(); 3871 3872 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3873 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3874 return SDValue(); 3875 3876 auto getRotateSource = [](SDValue X) { 3877 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3878 return X.getOperand(0); 3879 return SDValue(); 3880 }; 3881 3882 // Peek through a rotated value compared against 0 or -1: 3883 // (rot X, Y) == 0/-1 --> X == 0/-1 3884 // (rot X, Y) != 0/-1 --> X != 0/-1 3885 if (SDValue R = getRotateSource(N0)) 3886 return DAG.getSetCC(dl, VT, R, N1, Cond); 3887 3888 // Peek through an 'or' of a rotated value compared against 0: 3889 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 3890 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 3891 // 3892 // TODO: Add the 'and' with -1 sibling. 3893 // TODO: Recurse through a series of 'or' ops to find the rotate. 3894 EVT OpVT = N0.getValueType(); 3895 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 3896 if (SDValue R = getRotateSource(N0.getOperand(0))) { 3897 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 3898 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3899 } 3900 if (SDValue R = getRotateSource(N0.getOperand(1))) { 3901 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 3902 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3903 } 3904 } 3905 3906 return SDValue(); 3907 } 3908 3909 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 3910 ISD::CondCode Cond, const SDLoc &dl, 3911 SelectionDAG &DAG) { 3912 // If we are testing for all-bits-clear, we might be able to do that with 3913 // less shifting since bit-order does not matter. 3914 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3915 return SDValue(); 3916 3917 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3918 if (!C1 || !C1->isZero()) 3919 return SDValue(); 3920 3921 if (!N0.hasOneUse() || 3922 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 3923 return SDValue(); 3924 3925 unsigned BitWidth = N0.getScalarValueSizeInBits(); 3926 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 3927 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 3928 return SDValue(); 3929 3930 // Canonicalize fshr as fshl to reduce pattern-matching. 3931 unsigned ShAmt = ShAmtC->getZExtValue(); 3932 if (N0.getOpcode() == ISD::FSHR) 3933 ShAmt = BitWidth - ShAmt; 3934 3935 // Match an 'or' with a specific operand 'Other' in either commuted variant. 3936 SDValue X, Y; 3937 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 3938 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 3939 return false; 3940 if (Or.getOperand(0) == Other) { 3941 X = Or.getOperand(0); 3942 Y = Or.getOperand(1); 3943 return true; 3944 } 3945 if (Or.getOperand(1) == Other) { 3946 X = Or.getOperand(1); 3947 Y = Or.getOperand(0); 3948 return true; 3949 } 3950 return false; 3951 }; 3952 3953 EVT OpVT = N0.getValueType(); 3954 EVT ShAmtVT = N0.getOperand(2).getValueType(); 3955 SDValue F0 = N0.getOperand(0); 3956 SDValue F1 = N0.getOperand(1); 3957 if (matchOr(F0, F1)) { 3958 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 3959 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 3960 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 3961 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 3962 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3963 } 3964 if (matchOr(F1, F0)) { 3965 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 3966 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 3967 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 3968 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 3969 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3970 } 3971 3972 return SDValue(); 3973 } 3974 3975 /// Try to simplify a setcc built with the specified operands and cc. If it is 3976 /// unable to simplify it, return a null SDValue. 3977 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3978 ISD::CondCode Cond, bool foldBooleans, 3979 DAGCombinerInfo &DCI, 3980 const SDLoc &dl) const { 3981 SelectionDAG &DAG = DCI.DAG; 3982 const DataLayout &Layout = DAG.getDataLayout(); 3983 EVT OpVT = N0.getValueType(); 3984 3985 // Constant fold or commute setcc. 3986 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 3987 return Fold; 3988 3989 bool N0ConstOrSplat = 3990 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 3991 bool N1ConstOrSplat = 3992 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 3993 3994 // Ensure that the constant occurs on the RHS and fold constant comparisons. 3995 // TODO: Handle non-splat vector constants. All undef causes trouble. 3996 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 3997 // infinite loop here when we encounter one. 3998 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 3999 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4000 (DCI.isBeforeLegalizeOps() || 4001 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4002 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4003 4004 // If we have a subtract with the same 2 non-constant operands as this setcc 4005 // -- but in reverse order -- then try to commute the operands of this setcc 4006 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4007 // instruction on some targets. 4008 if (!N0ConstOrSplat && !N1ConstOrSplat && 4009 (DCI.isBeforeLegalizeOps() || 4010 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4011 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4012 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4013 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4014 4015 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4016 return V; 4017 4018 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4019 return V; 4020 4021 if (auto *N1C = isConstOrConstSplat(N1)) { 4022 const APInt &C1 = N1C->getAPIntValue(); 4023 4024 // Optimize some CTPOP cases. 4025 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4026 return V; 4027 4028 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4029 // equality comparison, then we're just comparing whether X itself is 4030 // zero. 4031 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4032 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4033 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4034 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4035 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4036 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4037 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4038 // (srl (ctlz x), 5) == 0 -> X != 0 4039 // (srl (ctlz x), 5) != 1 -> X != 0 4040 Cond = ISD::SETNE; 4041 } else { 4042 // (srl (ctlz x), 5) != 0 -> X == 0 4043 // (srl (ctlz x), 5) == 1 -> X == 0 4044 Cond = ISD::SETEQ; 4045 } 4046 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4047 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4048 Cond); 4049 } 4050 } 4051 } 4052 } 4053 4054 // FIXME: Support vectors. 4055 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4056 const APInt &C1 = N1C->getAPIntValue(); 4057 4058 // (zext x) == C --> x == (trunc C) 4059 // (sext x) == C --> x == (trunc C) 4060 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4061 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4062 unsigned MinBits = N0.getValueSizeInBits(); 4063 SDValue PreExt; 4064 bool Signed = false; 4065 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4066 // ZExt 4067 MinBits = N0->getOperand(0).getValueSizeInBits(); 4068 PreExt = N0->getOperand(0); 4069 } else if (N0->getOpcode() == ISD::AND) { 4070 // DAGCombine turns costly ZExts into ANDs 4071 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4072 if ((C->getAPIntValue()+1).isPowerOf2()) { 4073 MinBits = C->getAPIntValue().countTrailingOnes(); 4074 PreExt = N0->getOperand(0); 4075 } 4076 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4077 // SExt 4078 MinBits = N0->getOperand(0).getValueSizeInBits(); 4079 PreExt = N0->getOperand(0); 4080 Signed = true; 4081 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4082 // ZEXTLOAD / SEXTLOAD 4083 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4084 MinBits = LN0->getMemoryVT().getSizeInBits(); 4085 PreExt = N0; 4086 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4087 Signed = true; 4088 MinBits = LN0->getMemoryVT().getSizeInBits(); 4089 PreExt = N0; 4090 } 4091 } 4092 4093 // Figure out how many bits we need to preserve this constant. 4094 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4095 4096 // Make sure we're not losing bits from the constant. 4097 if (MinBits > 0 && 4098 MinBits < C1.getBitWidth() && 4099 MinBits >= ReqdBits) { 4100 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4101 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4102 // Will get folded away. 4103 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4104 if (MinBits == 1 && C1 == 1) 4105 // Invert the condition. 4106 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4107 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4108 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4109 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4110 } 4111 4112 // If truncating the setcc operands is not desirable, we can still 4113 // simplify the expression in some cases: 4114 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4115 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4116 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4117 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4118 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4119 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4120 SDValue TopSetCC = N0->getOperand(0); 4121 unsigned N0Opc = N0->getOpcode(); 4122 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4123 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4124 TopSetCC.getOpcode() == ISD::SETCC && 4125 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4126 (isConstFalseVal(N1) || 4127 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4128 4129 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4130 (!N1C->isZero() && Cond == ISD::SETNE); 4131 4132 if (!Inverse) 4133 return TopSetCC; 4134 4135 ISD::CondCode InvCond = ISD::getSetCCInverse( 4136 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4137 TopSetCC.getOperand(0).getValueType()); 4138 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4139 TopSetCC.getOperand(1), 4140 InvCond); 4141 } 4142 } 4143 } 4144 4145 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4146 // equality or unsigned, and all 1 bits of the const are in the same 4147 // partial word, see if we can shorten the load. 4148 if (DCI.isBeforeLegalize() && 4149 !ISD::isSignedIntSetCC(Cond) && 4150 N0.getOpcode() == ISD::AND && C1 == 0 && 4151 N0.getNode()->hasOneUse() && 4152 isa<LoadSDNode>(N0.getOperand(0)) && 4153 N0.getOperand(0).getNode()->hasOneUse() && 4154 isa<ConstantSDNode>(N0.getOperand(1))) { 4155 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4156 APInt bestMask; 4157 unsigned bestWidth = 0, bestOffset = 0; 4158 if (Lod->isSimple() && Lod->isUnindexed()) { 4159 unsigned origWidth = N0.getValueSizeInBits(); 4160 unsigned maskWidth = origWidth; 4161 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4162 // 8 bits, but have to be careful... 4163 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4164 origWidth = Lod->getMemoryVT().getSizeInBits(); 4165 const APInt &Mask = N0.getConstantOperandAPInt(1); 4166 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4167 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4168 for (unsigned offset=0; offset<origWidth/width; offset++) { 4169 if (Mask.isSubsetOf(newMask)) { 4170 if (Layout.isLittleEndian()) 4171 bestOffset = (uint64_t)offset * (width/8); 4172 else 4173 bestOffset = (origWidth/width - offset - 1) * (width/8); 4174 bestMask = Mask.lshr(offset * (width/8) * 8); 4175 bestWidth = width; 4176 break; 4177 } 4178 newMask <<= width; 4179 } 4180 } 4181 } 4182 if (bestWidth) { 4183 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4184 if (newVT.isRound() && 4185 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4186 SDValue Ptr = Lod->getBasePtr(); 4187 if (bestOffset != 0) 4188 Ptr = 4189 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4190 SDValue NewLoad = 4191 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4192 Lod->getPointerInfo().getWithOffset(bestOffset), 4193 Lod->getOriginalAlign()); 4194 return DAG.getSetCC(dl, VT, 4195 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4196 DAG.getConstant(bestMask.trunc(bestWidth), 4197 dl, newVT)), 4198 DAG.getConstant(0LL, dl, newVT), Cond); 4199 } 4200 } 4201 } 4202 4203 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4204 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4205 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4206 4207 // If the comparison constant has bits in the upper part, the 4208 // zero-extended value could never match. 4209 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4210 C1.getBitWidth() - InSize))) { 4211 switch (Cond) { 4212 case ISD::SETUGT: 4213 case ISD::SETUGE: 4214 case ISD::SETEQ: 4215 return DAG.getConstant(0, dl, VT); 4216 case ISD::SETULT: 4217 case ISD::SETULE: 4218 case ISD::SETNE: 4219 return DAG.getConstant(1, dl, VT); 4220 case ISD::SETGT: 4221 case ISD::SETGE: 4222 // True if the sign bit of C1 is set. 4223 return DAG.getConstant(C1.isNegative(), dl, VT); 4224 case ISD::SETLT: 4225 case ISD::SETLE: 4226 // True if the sign bit of C1 isn't set. 4227 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4228 default: 4229 break; 4230 } 4231 } 4232 4233 // Otherwise, we can perform the comparison with the low bits. 4234 switch (Cond) { 4235 case ISD::SETEQ: 4236 case ISD::SETNE: 4237 case ISD::SETUGT: 4238 case ISD::SETUGE: 4239 case ISD::SETULT: 4240 case ISD::SETULE: { 4241 EVT newVT = N0.getOperand(0).getValueType(); 4242 if (DCI.isBeforeLegalizeOps() || 4243 (isOperationLegal(ISD::SETCC, newVT) && 4244 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4245 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4246 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4247 4248 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4249 NewConst, Cond); 4250 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4251 } 4252 break; 4253 } 4254 default: 4255 break; // todo, be more careful with signed comparisons 4256 } 4257 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4258 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4259 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4260 OpVT)) { 4261 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4262 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4263 EVT ExtDstTy = N0.getValueType(); 4264 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4265 4266 // If the constant doesn't fit into the number of bits for the source of 4267 // the sign extension, it is impossible for both sides to be equal. 4268 if (C1.getMinSignedBits() > ExtSrcTyBits) 4269 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4270 4271 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4272 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4273 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4274 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4275 DAG.getConstant(Imm, dl, ExtDstTy)); 4276 if (!DCI.isCalledByLegalizer()) 4277 DCI.AddToWorklist(ZextOp.getNode()); 4278 // Otherwise, make this a use of a zext. 4279 return DAG.getSetCC(dl, VT, ZextOp, 4280 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4281 } else if ((N1C->isZero() || N1C->isOne()) && 4282 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4283 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4284 if (N0.getOpcode() == ISD::SETCC && 4285 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4286 (N0.getValueType() == MVT::i1 || 4287 getBooleanContents(N0.getOperand(0).getValueType()) == 4288 ZeroOrOneBooleanContent)) { 4289 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4290 if (TrueWhenTrue) 4291 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4292 // Invert the condition. 4293 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4294 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4295 if (DCI.isBeforeLegalizeOps() || 4296 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4297 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4298 } 4299 4300 if ((N0.getOpcode() == ISD::XOR || 4301 (N0.getOpcode() == ISD::AND && 4302 N0.getOperand(0).getOpcode() == ISD::XOR && 4303 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4304 isOneConstant(N0.getOperand(1))) { 4305 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4306 // can only do this if the top bits are known zero. 4307 unsigned BitWidth = N0.getValueSizeInBits(); 4308 if (DAG.MaskedValueIsZero(N0, 4309 APInt::getHighBitsSet(BitWidth, 4310 BitWidth-1))) { 4311 // Okay, get the un-inverted input value. 4312 SDValue Val; 4313 if (N0.getOpcode() == ISD::XOR) { 4314 Val = N0.getOperand(0); 4315 } else { 4316 assert(N0.getOpcode() == ISD::AND && 4317 N0.getOperand(0).getOpcode() == ISD::XOR); 4318 // ((X^1)&1)^1 -> X & 1 4319 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4320 N0.getOperand(0).getOperand(0), 4321 N0.getOperand(1)); 4322 } 4323 4324 return DAG.getSetCC(dl, VT, Val, N1, 4325 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4326 } 4327 } else if (N1C->isOne()) { 4328 SDValue Op0 = N0; 4329 if (Op0.getOpcode() == ISD::TRUNCATE) 4330 Op0 = Op0.getOperand(0); 4331 4332 if ((Op0.getOpcode() == ISD::XOR) && 4333 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4334 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4335 SDValue XorLHS = Op0.getOperand(0); 4336 SDValue XorRHS = Op0.getOperand(1); 4337 // Ensure that the input setccs return an i1 type or 0/1 value. 4338 if (Op0.getValueType() == MVT::i1 || 4339 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4340 ZeroOrOneBooleanContent && 4341 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4342 ZeroOrOneBooleanContent)) { 4343 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4344 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4345 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4346 } 4347 } 4348 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4349 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4350 if (Op0.getValueType().bitsGT(VT)) 4351 Op0 = DAG.getNode(ISD::AND, dl, VT, 4352 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4353 DAG.getConstant(1, dl, VT)); 4354 else if (Op0.getValueType().bitsLT(VT)) 4355 Op0 = DAG.getNode(ISD::AND, dl, VT, 4356 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4357 DAG.getConstant(1, dl, VT)); 4358 4359 return DAG.getSetCC(dl, VT, Op0, 4360 DAG.getConstant(0, dl, Op0.getValueType()), 4361 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4362 } 4363 if (Op0.getOpcode() == ISD::AssertZext && 4364 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4365 return DAG.getSetCC(dl, VT, Op0, 4366 DAG.getConstant(0, dl, Op0.getValueType()), 4367 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4368 } 4369 } 4370 4371 // Given: 4372 // icmp eq/ne (urem %x, %y), 0 4373 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4374 // icmp eq/ne %x, 0 4375 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4376 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4377 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4378 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4379 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4380 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4381 } 4382 4383 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4384 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4385 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4386 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4387 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4388 N1C && N1C->isAllOnes()) { 4389 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4390 DAG.getConstant(0, dl, OpVT), 4391 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4392 } 4393 4394 if (SDValue V = 4395 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4396 return V; 4397 } 4398 4399 // These simplifications apply to splat vectors as well. 4400 // TODO: Handle more splat vector cases. 4401 if (auto *N1C = isConstOrConstSplat(N1)) { 4402 const APInt &C1 = N1C->getAPIntValue(); 4403 4404 APInt MinVal, MaxVal; 4405 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4406 if (ISD::isSignedIntSetCC(Cond)) { 4407 MinVal = APInt::getSignedMinValue(OperandBitSize); 4408 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4409 } else { 4410 MinVal = APInt::getMinValue(OperandBitSize); 4411 MaxVal = APInt::getMaxValue(OperandBitSize); 4412 } 4413 4414 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4415 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4416 // X >= MIN --> true 4417 if (C1 == MinVal) 4418 return DAG.getBoolConstant(true, dl, VT, OpVT); 4419 4420 if (!VT.isVector()) { // TODO: Support this for vectors. 4421 // X >= C0 --> X > (C0 - 1) 4422 APInt C = C1 - 1; 4423 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4424 if ((DCI.isBeforeLegalizeOps() || 4425 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4426 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4427 isLegalICmpImmediate(C.getSExtValue())))) { 4428 return DAG.getSetCC(dl, VT, N0, 4429 DAG.getConstant(C, dl, N1.getValueType()), 4430 NewCC); 4431 } 4432 } 4433 } 4434 4435 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4436 // X <= MAX --> true 4437 if (C1 == MaxVal) 4438 return DAG.getBoolConstant(true, dl, VT, OpVT); 4439 4440 // X <= C0 --> X < (C0 + 1) 4441 if (!VT.isVector()) { // TODO: Support this for vectors. 4442 APInt C = C1 + 1; 4443 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4444 if ((DCI.isBeforeLegalizeOps() || 4445 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4446 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4447 isLegalICmpImmediate(C.getSExtValue())))) { 4448 return DAG.getSetCC(dl, VT, N0, 4449 DAG.getConstant(C, dl, N1.getValueType()), 4450 NewCC); 4451 } 4452 } 4453 } 4454 4455 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4456 if (C1 == MinVal) 4457 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4458 4459 // TODO: Support this for vectors after legalize ops. 4460 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4461 // Canonicalize setlt X, Max --> setne X, Max 4462 if (C1 == MaxVal) 4463 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4464 4465 // If we have setult X, 1, turn it into seteq X, 0 4466 if (C1 == MinVal+1) 4467 return DAG.getSetCC(dl, VT, N0, 4468 DAG.getConstant(MinVal, dl, N0.getValueType()), 4469 ISD::SETEQ); 4470 } 4471 } 4472 4473 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4474 if (C1 == MaxVal) 4475 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4476 4477 // TODO: Support this for vectors after legalize ops. 4478 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4479 // Canonicalize setgt X, Min --> setne X, Min 4480 if (C1 == MinVal) 4481 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4482 4483 // If we have setugt X, Max-1, turn it into seteq X, Max 4484 if (C1 == MaxVal-1) 4485 return DAG.getSetCC(dl, VT, N0, 4486 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4487 ISD::SETEQ); 4488 } 4489 } 4490 4491 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4492 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4493 if (C1.isZero()) 4494 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4495 VT, N0, N1, Cond, DCI, dl)) 4496 return CC; 4497 4498 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4499 // For example, when high 32-bits of i64 X are known clear: 4500 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4501 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4502 bool CmpZero = N1C->getAPIntValue().isZero(); 4503 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4504 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4505 // Match or(lo,shl(hi,bw/2)) pattern. 4506 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4507 unsigned EltBits = V.getScalarValueSizeInBits(); 4508 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4509 return false; 4510 SDValue LHS = V.getOperand(0); 4511 SDValue RHS = V.getOperand(1); 4512 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4513 // Unshifted element must have zero upperbits. 4514 if (RHS.getOpcode() == ISD::SHL && 4515 isa<ConstantSDNode>(RHS.getOperand(1)) && 4516 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4517 DAG.MaskedValueIsZero(LHS, HiBits)) { 4518 Lo = LHS; 4519 Hi = RHS.getOperand(0); 4520 return true; 4521 } 4522 if (LHS.getOpcode() == ISD::SHL && 4523 isa<ConstantSDNode>(LHS.getOperand(1)) && 4524 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4525 DAG.MaskedValueIsZero(RHS, HiBits)) { 4526 Lo = RHS; 4527 Hi = LHS.getOperand(0); 4528 return true; 4529 } 4530 return false; 4531 }; 4532 4533 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4534 unsigned EltBits = N0.getScalarValueSizeInBits(); 4535 unsigned HalfBits = EltBits / 2; 4536 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4537 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4538 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4539 SDValue NewN0 = 4540 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4541 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4542 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4543 }; 4544 4545 SDValue Lo, Hi; 4546 if (IsConcat(N0, Lo, Hi)) 4547 return MergeConcat(Lo, Hi); 4548 4549 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4550 SDValue Lo0, Lo1, Hi0, Hi1; 4551 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4552 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4553 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4554 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4555 } 4556 } 4557 } 4558 } 4559 4560 // If we have "setcc X, C0", check to see if we can shrink the immediate 4561 // by changing cc. 4562 // TODO: Support this for vectors after legalize ops. 4563 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4564 // SETUGT X, SINTMAX -> SETLT X, 0 4565 // SETUGE X, SINTMIN -> SETLT X, 0 4566 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4567 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4568 return DAG.getSetCC(dl, VT, N0, 4569 DAG.getConstant(0, dl, N1.getValueType()), 4570 ISD::SETLT); 4571 4572 // SETULT X, SINTMIN -> SETGT X, -1 4573 // SETULE X, SINTMAX -> SETGT X, -1 4574 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4575 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4576 return DAG.getSetCC(dl, VT, N0, 4577 DAG.getAllOnesConstant(dl, N1.getValueType()), 4578 ISD::SETGT); 4579 } 4580 } 4581 4582 // Back to non-vector simplifications. 4583 // TODO: Can we do these for vector splats? 4584 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4585 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4586 const APInt &C1 = N1C->getAPIntValue(); 4587 EVT ShValTy = N0.getValueType(); 4588 4589 // Fold bit comparisons when we can. This will result in an 4590 // incorrect value when boolean false is negative one, unless 4591 // the bitsize is 1 in which case the false value is the same 4592 // in practice regardless of the representation. 4593 if ((VT.getSizeInBits() == 1 || 4594 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4595 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4596 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4597 N0.getOpcode() == ISD::AND) { 4598 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4599 EVT ShiftTy = 4600 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4601 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4602 // Perform the xform if the AND RHS is a single bit. 4603 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4604 if (AndRHS->getAPIntValue().isPowerOf2() && 4605 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4606 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4607 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4608 DAG.getConstant(ShCt, dl, ShiftTy))); 4609 } 4610 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4611 // (X & 8) == 8 --> (X & 8) >> 3 4612 // Perform the xform if C1 is a single bit. 4613 unsigned ShCt = C1.logBase2(); 4614 if (C1.isPowerOf2() && 4615 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4616 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4617 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4618 DAG.getConstant(ShCt, dl, ShiftTy))); 4619 } 4620 } 4621 } 4622 } 4623 4624 if (C1.getMinSignedBits() <= 64 && 4625 !isLegalICmpImmediate(C1.getSExtValue())) { 4626 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4627 // (X & -256) == 256 -> (X >> 8) == 1 4628 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4629 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4630 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4631 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4632 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4633 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4634 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4635 SDValue Shift = 4636 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4637 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4638 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4639 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4640 } 4641 } 4642 } 4643 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4644 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4645 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4646 // X < 0x100000000 -> (X >> 32) < 1 4647 // X >= 0x100000000 -> (X >> 32) >= 1 4648 // X <= 0x0ffffffff -> (X >> 32) < 1 4649 // X > 0x0ffffffff -> (X >> 32) >= 1 4650 unsigned ShiftBits; 4651 APInt NewC = C1; 4652 ISD::CondCode NewCond = Cond; 4653 if (AdjOne) { 4654 ShiftBits = C1.countTrailingOnes(); 4655 NewC = NewC + 1; 4656 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4657 } else { 4658 ShiftBits = C1.countTrailingZeros(); 4659 } 4660 NewC.lshrInPlace(ShiftBits); 4661 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4662 isLegalICmpImmediate(NewC.getSExtValue()) && 4663 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4664 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4665 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4666 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4667 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4668 } 4669 } 4670 } 4671 } 4672 4673 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4674 auto *CFP = cast<ConstantFPSDNode>(N1); 4675 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4676 4677 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4678 // constant if knowing that the operand is non-nan is enough. We prefer to 4679 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4680 // materialize 0.0. 4681 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4682 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4683 4684 // setcc (fneg x), C -> setcc swap(pred) x, -C 4685 if (N0.getOpcode() == ISD::FNEG) { 4686 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4687 if (DCI.isBeforeLegalizeOps() || 4688 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4689 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4690 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4691 } 4692 } 4693 4694 // If the condition is not legal, see if we can find an equivalent one 4695 // which is legal. 4696 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4697 // If the comparison was an awkward floating-point == or != and one of 4698 // the comparison operands is infinity or negative infinity, convert the 4699 // condition to a less-awkward <= or >=. 4700 if (CFP->getValueAPF().isInfinity()) { 4701 bool IsNegInf = CFP->getValueAPF().isNegative(); 4702 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4703 switch (Cond) { 4704 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4705 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4706 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4707 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4708 default: break; 4709 } 4710 if (NewCond != ISD::SETCC_INVALID && 4711 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4712 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4713 } 4714 } 4715 } 4716 4717 if (N0 == N1) { 4718 // The sext(setcc()) => setcc() optimization relies on the appropriate 4719 // constant being emitted. 4720 assert(!N0.getValueType().isInteger() && 4721 "Integer types should be handled by FoldSetCC"); 4722 4723 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4724 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4725 if (UOF == 2) // FP operators that are undefined on NaNs. 4726 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4727 if (UOF == unsigned(EqTrue)) 4728 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4729 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4730 // if it is not already. 4731 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4732 if (NewCond != Cond && 4733 (DCI.isBeforeLegalizeOps() || 4734 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4735 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4736 } 4737 4738 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4739 N0.getValueType().isInteger()) { 4740 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4741 N0.getOpcode() == ISD::XOR) { 4742 // Simplify (X+Y) == (X+Z) --> Y == Z 4743 if (N0.getOpcode() == N1.getOpcode()) { 4744 if (N0.getOperand(0) == N1.getOperand(0)) 4745 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4746 if (N0.getOperand(1) == N1.getOperand(1)) 4747 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4748 if (isCommutativeBinOp(N0.getOpcode())) { 4749 // If X op Y == Y op X, try other combinations. 4750 if (N0.getOperand(0) == N1.getOperand(1)) 4751 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4752 Cond); 4753 if (N0.getOperand(1) == N1.getOperand(0)) 4754 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4755 Cond); 4756 } 4757 } 4758 4759 // If RHS is a legal immediate value for a compare instruction, we need 4760 // to be careful about increasing register pressure needlessly. 4761 bool LegalRHSImm = false; 4762 4763 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4764 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4765 // Turn (X+C1) == C2 --> X == C2-C1 4766 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4767 return DAG.getSetCC( 4768 dl, VT, N0.getOperand(0), 4769 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4770 dl, N0.getValueType()), 4771 Cond); 4772 4773 // Turn (X^C1) == C2 --> X == C1^C2 4774 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4775 return DAG.getSetCC( 4776 dl, VT, N0.getOperand(0), 4777 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4778 dl, N0.getValueType()), 4779 Cond); 4780 } 4781 4782 // Turn (C1-X) == C2 --> X == C1-C2 4783 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4784 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4785 return DAG.getSetCC( 4786 dl, VT, N0.getOperand(1), 4787 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4788 dl, N0.getValueType()), 4789 Cond); 4790 4791 // Could RHSC fold directly into a compare? 4792 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4793 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4794 } 4795 4796 // (X+Y) == X --> Y == 0 and similar folds. 4797 // Don't do this if X is an immediate that can fold into a cmp 4798 // instruction and X+Y has other uses. It could be an induction variable 4799 // chain, and the transform would increase register pressure. 4800 if (!LegalRHSImm || N0.hasOneUse()) 4801 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4802 return V; 4803 } 4804 4805 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4806 N1.getOpcode() == ISD::XOR) 4807 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4808 return V; 4809 4810 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4811 return V; 4812 } 4813 4814 // Fold remainder of division by a constant. 4815 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4816 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4817 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4818 4819 // When division is cheap or optimizing for minimum size, 4820 // fall through to DIVREM creation by skipping this fold. 4821 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4822 if (N0.getOpcode() == ISD::UREM) { 4823 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4824 return Folded; 4825 } else if (N0.getOpcode() == ISD::SREM) { 4826 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4827 return Folded; 4828 } 4829 } 4830 } 4831 4832 // Fold away ALL boolean setcc's. 4833 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4834 SDValue Temp; 4835 switch (Cond) { 4836 default: llvm_unreachable("Unknown integer setcc!"); 4837 case ISD::SETEQ: // X == Y -> ~(X^Y) 4838 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4839 N0 = DAG.getNOT(dl, Temp, OpVT); 4840 if (!DCI.isCalledByLegalizer()) 4841 DCI.AddToWorklist(Temp.getNode()); 4842 break; 4843 case ISD::SETNE: // X != Y --> (X^Y) 4844 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4845 break; 4846 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4847 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4848 Temp = DAG.getNOT(dl, N0, OpVT); 4849 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4850 if (!DCI.isCalledByLegalizer()) 4851 DCI.AddToWorklist(Temp.getNode()); 4852 break; 4853 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4854 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4855 Temp = DAG.getNOT(dl, N1, OpVT); 4856 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4857 if (!DCI.isCalledByLegalizer()) 4858 DCI.AddToWorklist(Temp.getNode()); 4859 break; 4860 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4861 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4862 Temp = DAG.getNOT(dl, N0, OpVT); 4863 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4864 if (!DCI.isCalledByLegalizer()) 4865 DCI.AddToWorklist(Temp.getNode()); 4866 break; 4867 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4868 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4869 Temp = DAG.getNOT(dl, N1, OpVT); 4870 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4871 break; 4872 } 4873 if (VT.getScalarType() != MVT::i1) { 4874 if (!DCI.isCalledByLegalizer()) 4875 DCI.AddToWorklist(N0.getNode()); 4876 // FIXME: If running after legalize, we probably can't do this. 4877 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4878 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4879 } 4880 return N0; 4881 } 4882 4883 // Could not fold it. 4884 return SDValue(); 4885 } 4886 4887 /// Returns true (and the GlobalValue and the offset) if the node is a 4888 /// GlobalAddress + offset. 4889 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4890 int64_t &Offset) const { 4891 4892 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4893 4894 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4895 GA = GASD->getGlobal(); 4896 Offset += GASD->getOffset(); 4897 return true; 4898 } 4899 4900 if (N->getOpcode() == ISD::ADD) { 4901 SDValue N1 = N->getOperand(0); 4902 SDValue N2 = N->getOperand(1); 4903 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4904 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4905 Offset += V->getSExtValue(); 4906 return true; 4907 } 4908 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4909 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4910 Offset += V->getSExtValue(); 4911 return true; 4912 } 4913 } 4914 } 4915 4916 return false; 4917 } 4918 4919 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4920 DAGCombinerInfo &DCI) const { 4921 // Default implementation: no optimization. 4922 return SDValue(); 4923 } 4924 4925 //===----------------------------------------------------------------------===// 4926 // Inline Assembler Implementation Methods 4927 //===----------------------------------------------------------------------===// 4928 4929 TargetLowering::ConstraintType 4930 TargetLowering::getConstraintType(StringRef Constraint) const { 4931 unsigned S = Constraint.size(); 4932 4933 if (S == 1) { 4934 switch (Constraint[0]) { 4935 default: break; 4936 case 'r': 4937 return C_RegisterClass; 4938 case 'm': // memory 4939 case 'o': // offsetable 4940 case 'V': // not offsetable 4941 return C_Memory; 4942 case 'p': // Address. 4943 return C_Address; 4944 case 'n': // Simple Integer 4945 case 'E': // Floating Point Constant 4946 case 'F': // Floating Point Constant 4947 return C_Immediate; 4948 case 'i': // Simple Integer or Relocatable Constant 4949 case 's': // Relocatable Constant 4950 case 'X': // Allow ANY value. 4951 case 'I': // Target registers. 4952 case 'J': 4953 case 'K': 4954 case 'L': 4955 case 'M': 4956 case 'N': 4957 case 'O': 4958 case 'P': 4959 case '<': 4960 case '>': 4961 return C_Other; 4962 } 4963 } 4964 4965 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4966 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4967 return C_Memory; 4968 return C_Register; 4969 } 4970 return C_Unknown; 4971 } 4972 4973 /// Try to replace an X constraint, which matches anything, with another that 4974 /// has more specific requirements based on the type of the corresponding 4975 /// operand. 4976 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4977 if (ConstraintVT.isInteger()) 4978 return "r"; 4979 if (ConstraintVT.isFloatingPoint()) 4980 return "f"; // works for many targets 4981 return nullptr; 4982 } 4983 4984 SDValue TargetLowering::LowerAsmOutputForConstraint( 4985 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4986 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4987 return SDValue(); 4988 } 4989 4990 /// Lower the specified operand into the Ops vector. 4991 /// If it is invalid, don't add anything to Ops. 4992 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4993 std::string &Constraint, 4994 std::vector<SDValue> &Ops, 4995 SelectionDAG &DAG) const { 4996 4997 if (Constraint.length() > 1) return; 4998 4999 char ConstraintLetter = Constraint[0]; 5000 switch (ConstraintLetter) { 5001 default: break; 5002 case 'X': // Allows any operand 5003 case 'i': // Simple Integer or Relocatable Constant 5004 case 'n': // Simple Integer 5005 case 's': { // Relocatable Constant 5006 5007 ConstantSDNode *C; 5008 uint64_t Offset = 0; 5009 5010 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5011 // etc., since getelementpointer is variadic. We can't use 5012 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5013 // while in this case the GA may be furthest from the root node which is 5014 // likely an ISD::ADD. 5015 while (true) { 5016 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5017 // gcc prints these as sign extended. Sign extend value to 64 bits 5018 // now; without this it would get ZExt'd later in 5019 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5020 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5021 BooleanContent BCont = getBooleanContents(MVT::i64); 5022 ISD::NodeType ExtOpc = 5023 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5024 int64_t ExtVal = 5025 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5026 Ops.push_back( 5027 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5028 return; 5029 } 5030 if (ConstraintLetter != 'n') { 5031 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5032 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5033 GA->getValueType(0), 5034 Offset + GA->getOffset())); 5035 return; 5036 } 5037 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5038 Ops.push_back(DAG.getTargetBlockAddress( 5039 BA->getBlockAddress(), BA->getValueType(0), 5040 Offset + BA->getOffset(), BA->getTargetFlags())); 5041 return; 5042 } 5043 if (isa<BasicBlockSDNode>(Op)) { 5044 Ops.push_back(Op); 5045 return; 5046 } 5047 } 5048 const unsigned OpCode = Op.getOpcode(); 5049 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5050 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5051 Op = Op.getOperand(1); 5052 // Subtraction is not commutative. 5053 else if (OpCode == ISD::ADD && 5054 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5055 Op = Op.getOperand(0); 5056 else 5057 return; 5058 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5059 continue; 5060 } 5061 return; 5062 } 5063 break; 5064 } 5065 } 5066 } 5067 5068 std::pair<unsigned, const TargetRegisterClass *> 5069 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5070 StringRef Constraint, 5071 MVT VT) const { 5072 if (Constraint.empty() || Constraint[0] != '{') 5073 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5074 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5075 5076 // Remove the braces from around the name. 5077 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5078 5079 std::pair<unsigned, const TargetRegisterClass *> R = 5080 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5081 5082 // Figure out which register class contains this reg. 5083 for (const TargetRegisterClass *RC : RI->regclasses()) { 5084 // If none of the value types for this register class are valid, we 5085 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5086 if (!isLegalRC(*RI, *RC)) 5087 continue; 5088 5089 for (const MCPhysReg &PR : *RC) { 5090 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5091 std::pair<unsigned, const TargetRegisterClass *> S = 5092 std::make_pair(PR, RC); 5093 5094 // If this register class has the requested value type, return it, 5095 // otherwise keep searching and return the first class found 5096 // if no other is found which explicitly has the requested type. 5097 if (RI->isTypeLegalForClass(*RC, VT)) 5098 return S; 5099 if (!R.second) 5100 R = S; 5101 } 5102 } 5103 } 5104 5105 return R; 5106 } 5107 5108 //===----------------------------------------------------------------------===// 5109 // Constraint Selection. 5110 5111 /// Return true of this is an input operand that is a matching constraint like 5112 /// "4". 5113 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5114 assert(!ConstraintCode.empty() && "No known constraint!"); 5115 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5116 } 5117 5118 /// If this is an input matching constraint, this method returns the output 5119 /// operand it matches. 5120 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5121 assert(!ConstraintCode.empty() && "No known constraint!"); 5122 return atoi(ConstraintCode.c_str()); 5123 } 5124 5125 /// Split up the constraint string from the inline assembly value into the 5126 /// specific constraints and their prefixes, and also tie in the associated 5127 /// operand values. 5128 /// If this returns an empty vector, and if the constraint string itself 5129 /// isn't empty, there was an error parsing. 5130 TargetLowering::AsmOperandInfoVector 5131 TargetLowering::ParseConstraints(const DataLayout &DL, 5132 const TargetRegisterInfo *TRI, 5133 const CallBase &Call) const { 5134 /// Information about all of the constraints. 5135 AsmOperandInfoVector ConstraintOperands; 5136 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5137 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5138 5139 // Do a prepass over the constraints, canonicalizing them, and building up the 5140 // ConstraintOperands list. 5141 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5142 unsigned ResNo = 0; // ResNo - The result number of the next output. 5143 5144 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5145 ConstraintOperands.emplace_back(std::move(CI)); 5146 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5147 5148 // Update multiple alternative constraint count. 5149 if (OpInfo.multipleAlternatives.size() > maCount) 5150 maCount = OpInfo.multipleAlternatives.size(); 5151 5152 OpInfo.ConstraintVT = MVT::Other; 5153 5154 // Compute the value type for each operand. 5155 switch (OpInfo.Type) { 5156 case InlineAsm::isOutput: 5157 // Indirect outputs just consume an argument. 5158 if (OpInfo.isIndirect) { 5159 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5160 break; 5161 } 5162 5163 // The return value of the call is this value. As such, there is no 5164 // corresponding argument. 5165 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5166 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5167 OpInfo.ConstraintVT = 5168 getSimpleValueType(DL, STy->getElementType(ResNo)); 5169 } else { 5170 assert(ResNo == 0 && "Asm only has one result!"); 5171 OpInfo.ConstraintVT = 5172 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5173 } 5174 ++ResNo; 5175 break; 5176 case InlineAsm::isInput: 5177 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5178 break; 5179 case InlineAsm::isClobber: 5180 // Nothing to do. 5181 break; 5182 } 5183 5184 if (OpInfo.CallOperandVal) { 5185 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5186 if (OpInfo.isIndirect) { 5187 OpTy = Call.getParamElementType(ArgNo); 5188 assert(OpTy && "Indirect operand must have elementtype attribute"); 5189 } 5190 5191 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5192 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5193 if (STy->getNumElements() == 1) 5194 OpTy = STy->getElementType(0); 5195 5196 // If OpTy is not a single value, it may be a struct/union that we 5197 // can tile with integers. 5198 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5199 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5200 switch (BitSize) { 5201 default: break; 5202 case 1: 5203 case 8: 5204 case 16: 5205 case 32: 5206 case 64: 5207 case 128: 5208 OpInfo.ConstraintVT = 5209 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 5210 break; 5211 } 5212 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 5213 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 5214 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 5215 } else { 5216 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 5217 } 5218 5219 ArgNo++; 5220 } 5221 } 5222 5223 // If we have multiple alternative constraints, select the best alternative. 5224 if (!ConstraintOperands.empty()) { 5225 if (maCount) { 5226 unsigned bestMAIndex = 0; 5227 int bestWeight = -1; 5228 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5229 int weight = -1; 5230 unsigned maIndex; 5231 // Compute the sums of the weights for each alternative, keeping track 5232 // of the best (highest weight) one so far. 5233 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5234 int weightSum = 0; 5235 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5236 cIndex != eIndex; ++cIndex) { 5237 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5238 if (OpInfo.Type == InlineAsm::isClobber) 5239 continue; 5240 5241 // If this is an output operand with a matching input operand, 5242 // look up the matching input. If their types mismatch, e.g. one 5243 // is an integer, the other is floating point, or their sizes are 5244 // different, flag it as an maCantMatch. 5245 if (OpInfo.hasMatchingInput()) { 5246 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5247 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5248 if ((OpInfo.ConstraintVT.isInteger() != 5249 Input.ConstraintVT.isInteger()) || 5250 (OpInfo.ConstraintVT.getSizeInBits() != 5251 Input.ConstraintVT.getSizeInBits())) { 5252 weightSum = -1; // Can't match. 5253 break; 5254 } 5255 } 5256 } 5257 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5258 if (weight == -1) { 5259 weightSum = -1; 5260 break; 5261 } 5262 weightSum += weight; 5263 } 5264 // Update best. 5265 if (weightSum > bestWeight) { 5266 bestWeight = weightSum; 5267 bestMAIndex = maIndex; 5268 } 5269 } 5270 5271 // Now select chosen alternative in each constraint. 5272 for (AsmOperandInfo &cInfo : ConstraintOperands) 5273 if (cInfo.Type != InlineAsm::isClobber) 5274 cInfo.selectAlternative(bestMAIndex); 5275 } 5276 } 5277 5278 // Check and hook up tied operands, choose constraint code to use. 5279 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5280 cIndex != eIndex; ++cIndex) { 5281 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5282 5283 // If this is an output operand with a matching input operand, look up the 5284 // matching input. If their types mismatch, e.g. one is an integer, the 5285 // other is floating point, or their sizes are different, flag it as an 5286 // error. 5287 if (OpInfo.hasMatchingInput()) { 5288 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5289 5290 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5291 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5292 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5293 OpInfo.ConstraintVT); 5294 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5295 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5296 Input.ConstraintVT); 5297 if ((OpInfo.ConstraintVT.isInteger() != 5298 Input.ConstraintVT.isInteger()) || 5299 (MatchRC.second != InputRC.second)) { 5300 report_fatal_error("Unsupported asm: input constraint" 5301 " with a matching output constraint of" 5302 " incompatible type!"); 5303 } 5304 } 5305 } 5306 } 5307 5308 return ConstraintOperands; 5309 } 5310 5311 /// Return an integer indicating how general CT is. 5312 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5313 switch (CT) { 5314 case TargetLowering::C_Immediate: 5315 case TargetLowering::C_Other: 5316 case TargetLowering::C_Unknown: 5317 return 0; 5318 case TargetLowering::C_Register: 5319 return 1; 5320 case TargetLowering::C_RegisterClass: 5321 return 2; 5322 case TargetLowering::C_Memory: 5323 case TargetLowering::C_Address: 5324 return 3; 5325 } 5326 llvm_unreachable("Invalid constraint type"); 5327 } 5328 5329 /// Examine constraint type and operand type and determine a weight value. 5330 /// This object must already have been set up with the operand type 5331 /// and the current alternative constraint selected. 5332 TargetLowering::ConstraintWeight 5333 TargetLowering::getMultipleConstraintMatchWeight( 5334 AsmOperandInfo &info, int maIndex) const { 5335 InlineAsm::ConstraintCodeVector *rCodes; 5336 if (maIndex >= (int)info.multipleAlternatives.size()) 5337 rCodes = &info.Codes; 5338 else 5339 rCodes = &info.multipleAlternatives[maIndex].Codes; 5340 ConstraintWeight BestWeight = CW_Invalid; 5341 5342 // Loop over the options, keeping track of the most general one. 5343 for (const std::string &rCode : *rCodes) { 5344 ConstraintWeight weight = 5345 getSingleConstraintMatchWeight(info, rCode.c_str()); 5346 if (weight > BestWeight) 5347 BestWeight = weight; 5348 } 5349 5350 return BestWeight; 5351 } 5352 5353 /// Examine constraint type and operand type and determine a weight value. 5354 /// This object must already have been set up with the operand type 5355 /// and the current alternative constraint selected. 5356 TargetLowering::ConstraintWeight 5357 TargetLowering::getSingleConstraintMatchWeight( 5358 AsmOperandInfo &info, const char *constraint) const { 5359 ConstraintWeight weight = CW_Invalid; 5360 Value *CallOperandVal = info.CallOperandVal; 5361 // If we don't have a value, we can't do a match, 5362 // but allow it at the lowest weight. 5363 if (!CallOperandVal) 5364 return CW_Default; 5365 // Look at the constraint type. 5366 switch (*constraint) { 5367 case 'i': // immediate integer. 5368 case 'n': // immediate integer with a known value. 5369 if (isa<ConstantInt>(CallOperandVal)) 5370 weight = CW_Constant; 5371 break; 5372 case 's': // non-explicit intregal immediate. 5373 if (isa<GlobalValue>(CallOperandVal)) 5374 weight = CW_Constant; 5375 break; 5376 case 'E': // immediate float if host format. 5377 case 'F': // immediate float. 5378 if (isa<ConstantFP>(CallOperandVal)) 5379 weight = CW_Constant; 5380 break; 5381 case '<': // memory operand with autodecrement. 5382 case '>': // memory operand with autoincrement. 5383 case 'm': // memory operand. 5384 case 'o': // offsettable memory operand 5385 case 'V': // non-offsettable memory operand 5386 weight = CW_Memory; 5387 break; 5388 case 'r': // general register. 5389 case 'g': // general register, memory operand or immediate integer. 5390 // note: Clang converts "g" to "imr". 5391 if (CallOperandVal->getType()->isIntegerTy()) 5392 weight = CW_Register; 5393 break; 5394 case 'X': // any operand. 5395 default: 5396 weight = CW_Default; 5397 break; 5398 } 5399 return weight; 5400 } 5401 5402 /// If there are multiple different constraints that we could pick for this 5403 /// operand (e.g. "imr") try to pick the 'best' one. 5404 /// This is somewhat tricky: constraints fall into four classes: 5405 /// Other -> immediates and magic values 5406 /// Register -> one specific register 5407 /// RegisterClass -> a group of regs 5408 /// Memory -> memory 5409 /// Ideally, we would pick the most specific constraint possible: if we have 5410 /// something that fits into a register, we would pick it. The problem here 5411 /// is that if we have something that could either be in a register or in 5412 /// memory that use of the register could cause selection of *other* 5413 /// operands to fail: they might only succeed if we pick memory. Because of 5414 /// this the heuristic we use is: 5415 /// 5416 /// 1) If there is an 'other' constraint, and if the operand is valid for 5417 /// that constraint, use it. This makes us take advantage of 'i' 5418 /// constraints when available. 5419 /// 2) Otherwise, pick the most general constraint present. This prefers 5420 /// 'm' over 'r', for example. 5421 /// 5422 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5423 const TargetLowering &TLI, 5424 SDValue Op, SelectionDAG *DAG) { 5425 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5426 unsigned BestIdx = 0; 5427 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5428 int BestGenerality = -1; 5429 5430 // Loop over the options, keeping track of the most general one. 5431 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5432 TargetLowering::ConstraintType CType = 5433 TLI.getConstraintType(OpInfo.Codes[i]); 5434 5435 // Indirect 'other' or 'immediate' constraints are not allowed. 5436 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5437 CType == TargetLowering::C_Register || 5438 CType == TargetLowering::C_RegisterClass)) 5439 continue; 5440 5441 // If this is an 'other' or 'immediate' constraint, see if the operand is 5442 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5443 // the operand is an integer in the range [0..31] we want to use I (saving a 5444 // load of a register), otherwise we must use 'r'. 5445 if ((CType == TargetLowering::C_Other || 5446 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5447 assert(OpInfo.Codes[i].size() == 1 && 5448 "Unhandled multi-letter 'other' constraint"); 5449 std::vector<SDValue> ResultOps; 5450 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5451 ResultOps, *DAG); 5452 if (!ResultOps.empty()) { 5453 BestType = CType; 5454 BestIdx = i; 5455 break; 5456 } 5457 } 5458 5459 // Things with matching constraints can only be registers, per gcc 5460 // documentation. This mainly affects "g" constraints. 5461 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5462 continue; 5463 5464 // This constraint letter is more general than the previous one, use it. 5465 int Generality = getConstraintGenerality(CType); 5466 if (Generality > BestGenerality) { 5467 BestType = CType; 5468 BestIdx = i; 5469 BestGenerality = Generality; 5470 } 5471 } 5472 5473 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5474 OpInfo.ConstraintType = BestType; 5475 } 5476 5477 /// Determines the constraint code and constraint type to use for the specific 5478 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5479 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5480 SDValue Op, 5481 SelectionDAG *DAG) const { 5482 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5483 5484 // Single-letter constraints ('r') are very common. 5485 if (OpInfo.Codes.size() == 1) { 5486 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5487 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5488 } else { 5489 ChooseConstraint(OpInfo, *this, Op, DAG); 5490 } 5491 5492 // 'X' matches anything. 5493 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5494 // Constants are handled elsewhere. For Functions, the type here is the 5495 // type of the result, which is not what we want to look at; leave them 5496 // alone. 5497 Value *v = OpInfo.CallOperandVal; 5498 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5499 return; 5500 } 5501 5502 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5503 OpInfo.ConstraintCode = "i"; 5504 return; 5505 } 5506 5507 // Otherwise, try to resolve it to something we know about by looking at 5508 // the actual operand type. 5509 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5510 OpInfo.ConstraintCode = Repl; 5511 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5512 } 5513 } 5514 } 5515 5516 /// Given an exact SDIV by a constant, create a multiplication 5517 /// with the multiplicative inverse of the constant. 5518 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5519 const SDLoc &dl, SelectionDAG &DAG, 5520 SmallVectorImpl<SDNode *> &Created) { 5521 SDValue Op0 = N->getOperand(0); 5522 SDValue Op1 = N->getOperand(1); 5523 EVT VT = N->getValueType(0); 5524 EVT SVT = VT.getScalarType(); 5525 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5526 EVT ShSVT = ShVT.getScalarType(); 5527 5528 bool UseSRA = false; 5529 SmallVector<SDValue, 16> Shifts, Factors; 5530 5531 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5532 if (C->isZero()) 5533 return false; 5534 APInt Divisor = C->getAPIntValue(); 5535 unsigned Shift = Divisor.countTrailingZeros(); 5536 if (Shift) { 5537 Divisor.ashrInPlace(Shift); 5538 UseSRA = true; 5539 } 5540 // Calculate the multiplicative inverse, using Newton's method. 5541 APInt t; 5542 APInt Factor = Divisor; 5543 while ((t = Divisor * Factor) != 1) 5544 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5545 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5546 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5547 return true; 5548 }; 5549 5550 // Collect all magic values from the build vector. 5551 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5552 return SDValue(); 5553 5554 SDValue Shift, Factor; 5555 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5556 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5557 Factor = DAG.getBuildVector(VT, dl, Factors); 5558 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5559 assert(Shifts.size() == 1 && Factors.size() == 1 && 5560 "Expected matchUnaryPredicate to return one element for scalable " 5561 "vectors"); 5562 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5563 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5564 } else { 5565 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5566 Shift = Shifts[0]; 5567 Factor = Factors[0]; 5568 } 5569 5570 SDValue Res = Op0; 5571 5572 // Shift the value upfront if it is even, so the LSB is one. 5573 if (UseSRA) { 5574 // TODO: For UDIV use SRL instead of SRA. 5575 SDNodeFlags Flags; 5576 Flags.setExact(true); 5577 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5578 Created.push_back(Res.getNode()); 5579 } 5580 5581 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5582 } 5583 5584 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5585 SelectionDAG &DAG, 5586 SmallVectorImpl<SDNode *> &Created) const { 5587 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5589 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5590 return SDValue(N, 0); // Lower SDIV as SDIV 5591 return SDValue(); 5592 } 5593 5594 SDValue 5595 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5596 SelectionDAG &DAG, 5597 SmallVectorImpl<SDNode *> &Created) const { 5598 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5600 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5601 return SDValue(N, 0); // Lower SREM as SREM 5602 return SDValue(); 5603 } 5604 5605 /// Given an ISD::SDIV node expressing a divide by constant, 5606 /// return a DAG expression to select that will generate the same value by 5607 /// multiplying by a magic number. 5608 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5609 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5610 bool IsAfterLegalization, 5611 SmallVectorImpl<SDNode *> &Created) const { 5612 SDLoc dl(N); 5613 EVT VT = N->getValueType(0); 5614 EVT SVT = VT.getScalarType(); 5615 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5616 EVT ShSVT = ShVT.getScalarType(); 5617 unsigned EltBits = VT.getScalarSizeInBits(); 5618 EVT MulVT; 5619 5620 // Check to see if we can do this. 5621 // FIXME: We should be more aggressive here. 5622 if (!isTypeLegal(VT)) { 5623 // Limit this to simple scalars for now. 5624 if (VT.isVector() || !VT.isSimple()) 5625 return SDValue(); 5626 5627 // If this type will be promoted to a large enough type with a legal 5628 // multiply operation, we can go ahead and do this transform. 5629 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5630 return SDValue(); 5631 5632 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5633 if (MulVT.getSizeInBits() < (2 * EltBits) || 5634 !isOperationLegal(ISD::MUL, MulVT)) 5635 return SDValue(); 5636 } 5637 5638 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5639 if (N->getFlags().hasExact()) 5640 return BuildExactSDIV(*this, N, dl, DAG, Created); 5641 5642 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5643 5644 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5645 if (C->isZero()) 5646 return false; 5647 5648 const APInt &Divisor = C->getAPIntValue(); 5649 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5650 int NumeratorFactor = 0; 5651 int ShiftMask = -1; 5652 5653 if (Divisor.isOne() || Divisor.isAllOnes()) { 5654 // If d is +1/-1, we just multiply the numerator by +1/-1. 5655 NumeratorFactor = Divisor.getSExtValue(); 5656 magics.Magic = 0; 5657 magics.ShiftAmount = 0; 5658 ShiftMask = 0; 5659 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5660 // If d > 0 and m < 0, add the numerator. 5661 NumeratorFactor = 1; 5662 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5663 // If d < 0 and m > 0, subtract the numerator. 5664 NumeratorFactor = -1; 5665 } 5666 5667 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5668 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5669 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5670 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5671 return true; 5672 }; 5673 5674 SDValue N0 = N->getOperand(0); 5675 SDValue N1 = N->getOperand(1); 5676 5677 // Collect the shifts / magic values from each element. 5678 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5679 return SDValue(); 5680 5681 SDValue MagicFactor, Factor, Shift, ShiftMask; 5682 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5683 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5684 Factor = DAG.getBuildVector(VT, dl, Factors); 5685 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5686 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5687 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5688 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5689 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5690 "Expected matchUnaryPredicate to return one element for scalable " 5691 "vectors"); 5692 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5693 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5694 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5695 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5696 } else { 5697 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5698 MagicFactor = MagicFactors[0]; 5699 Factor = Factors[0]; 5700 Shift = Shifts[0]; 5701 ShiftMask = ShiftMasks[0]; 5702 } 5703 5704 // Multiply the numerator (operand 0) by the magic value. 5705 // FIXME: We should support doing a MUL in a wider type. 5706 auto GetMULHS = [&](SDValue X, SDValue Y) { 5707 // If the type isn't legal, use a wider mul of the the type calculated 5708 // earlier. 5709 if (!isTypeLegal(VT)) { 5710 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5711 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5712 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5713 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5714 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5715 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5716 } 5717 5718 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5719 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5720 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5721 SDValue LoHi = 5722 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5723 return SDValue(LoHi.getNode(), 1); 5724 } 5725 return SDValue(); 5726 }; 5727 5728 SDValue Q = GetMULHS(N0, MagicFactor); 5729 if (!Q) 5730 return SDValue(); 5731 5732 Created.push_back(Q.getNode()); 5733 5734 // (Optionally) Add/subtract the numerator using Factor. 5735 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5736 Created.push_back(Factor.getNode()); 5737 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5738 Created.push_back(Q.getNode()); 5739 5740 // Shift right algebraic by shift value. 5741 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5742 Created.push_back(Q.getNode()); 5743 5744 // Extract the sign bit, mask it and add it to the quotient. 5745 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5746 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5747 Created.push_back(T.getNode()); 5748 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5749 Created.push_back(T.getNode()); 5750 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5751 } 5752 5753 /// Given an ISD::UDIV node expressing a divide by constant, 5754 /// return a DAG expression to select that will generate the same value by 5755 /// multiplying by a magic number. 5756 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5757 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5758 bool IsAfterLegalization, 5759 SmallVectorImpl<SDNode *> &Created) const { 5760 SDLoc dl(N); 5761 EVT VT = N->getValueType(0); 5762 EVT SVT = VT.getScalarType(); 5763 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5764 EVT ShSVT = ShVT.getScalarType(); 5765 unsigned EltBits = VT.getScalarSizeInBits(); 5766 EVT MulVT; 5767 5768 // Check to see if we can do this. 5769 // FIXME: We should be more aggressive here. 5770 if (!isTypeLegal(VT)) { 5771 // Limit this to simple scalars for now. 5772 if (VT.isVector() || !VT.isSimple()) 5773 return SDValue(); 5774 5775 // If this type will be promoted to a large enough type with a legal 5776 // multiply operation, we can go ahead and do this transform. 5777 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5778 return SDValue(); 5779 5780 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5781 if (MulVT.getSizeInBits() < (2 * EltBits) || 5782 !isOperationLegal(ISD::MUL, MulVT)) 5783 return SDValue(); 5784 } 5785 5786 bool UseNPQ = false; 5787 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5788 5789 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5790 if (C->isZero()) 5791 return false; 5792 // FIXME: We should use a narrower constant when the upper 5793 // bits are known to be zero. 5794 const APInt& Divisor = C->getAPIntValue(); 5795 UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor); 5796 unsigned PreShift = 0, PostShift = 0; 5797 5798 // If the divisor is even, we can avoid using the expensive fixup by 5799 // shifting the divided value upfront. 5800 if (magics.IsAdd != 0 && !Divisor[0]) { 5801 PreShift = Divisor.countTrailingZeros(); 5802 // Get magic number for the shifted divisor. 5803 magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5804 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 5805 } 5806 5807 APInt Magic = magics.Magic; 5808 5809 unsigned SelNPQ; 5810 if (magics.IsAdd == 0 || Divisor.isOne()) { 5811 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5812 "We shouldn't generate an undefined shift!"); 5813 PostShift = magics.ShiftAmount; 5814 SelNPQ = false; 5815 } else { 5816 PostShift = magics.ShiftAmount - 1; 5817 SelNPQ = true; 5818 } 5819 5820 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5821 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5822 NPQFactors.push_back( 5823 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5824 : APInt::getZero(EltBits), 5825 dl, SVT)); 5826 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5827 UseNPQ |= SelNPQ; 5828 return true; 5829 }; 5830 5831 SDValue N0 = N->getOperand(0); 5832 SDValue N1 = N->getOperand(1); 5833 5834 // Collect the shifts/magic values from each element. 5835 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5836 return SDValue(); 5837 5838 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5839 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5840 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5841 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5842 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5843 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5844 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5845 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5846 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5847 "Expected matchUnaryPredicate to return one for scalable vectors"); 5848 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5849 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5850 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5851 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5852 } else { 5853 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5854 PreShift = PreShifts[0]; 5855 MagicFactor = MagicFactors[0]; 5856 PostShift = PostShifts[0]; 5857 } 5858 5859 SDValue Q = N0; 5860 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5861 Created.push_back(Q.getNode()); 5862 5863 // FIXME: We should support doing a MUL in a wider type. 5864 auto GetMULHU = [&](SDValue X, SDValue Y) { 5865 // If the type isn't legal, use a wider mul of the the type calculated 5866 // earlier. 5867 if (!isTypeLegal(VT)) { 5868 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5869 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5870 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5871 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5872 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5873 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5874 } 5875 5876 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5877 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5878 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5879 SDValue LoHi = 5880 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5881 return SDValue(LoHi.getNode(), 1); 5882 } 5883 return SDValue(); // No mulhu or equivalent 5884 }; 5885 5886 // Multiply the numerator (operand 0) by the magic value. 5887 Q = GetMULHU(Q, MagicFactor); 5888 if (!Q) 5889 return SDValue(); 5890 5891 Created.push_back(Q.getNode()); 5892 5893 if (UseNPQ) { 5894 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5895 Created.push_back(NPQ.getNode()); 5896 5897 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5898 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5899 if (VT.isVector()) 5900 NPQ = GetMULHU(NPQ, NPQFactor); 5901 else 5902 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5903 5904 Created.push_back(NPQ.getNode()); 5905 5906 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5907 Created.push_back(Q.getNode()); 5908 } 5909 5910 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5911 Created.push_back(Q.getNode()); 5912 5913 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5914 5915 SDValue One = DAG.getConstant(1, dl, VT); 5916 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5917 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5918 } 5919 5920 /// If all values in Values that *don't* match the predicate are same 'splat' 5921 /// value, then replace all values with that splat value. 5922 /// Else, if AlternativeReplacement was provided, then replace all values that 5923 /// do match predicate with AlternativeReplacement value. 5924 static void 5925 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5926 std::function<bool(SDValue)> Predicate, 5927 SDValue AlternativeReplacement = SDValue()) { 5928 SDValue Replacement; 5929 // Is there a value for which the Predicate does *NOT* match? What is it? 5930 auto SplatValue = llvm::find_if_not(Values, Predicate); 5931 if (SplatValue != Values.end()) { 5932 // Does Values consist only of SplatValue's and values matching Predicate? 5933 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5934 return Value == *SplatValue || Predicate(Value); 5935 })) // Then we shall replace values matching predicate with SplatValue. 5936 Replacement = *SplatValue; 5937 } 5938 if (!Replacement) { 5939 // Oops, we did not find the "baseline" splat value. 5940 if (!AlternativeReplacement) 5941 return; // Nothing to do. 5942 // Let's replace with provided value then. 5943 Replacement = AlternativeReplacement; 5944 } 5945 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5946 } 5947 5948 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5949 /// where the divisor is constant and the comparison target is zero, 5950 /// return a DAG expression that will generate the same comparison result 5951 /// using only multiplications, additions and shifts/rotations. 5952 /// Ref: "Hacker's Delight" 10-17. 5953 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5954 SDValue CompTargetNode, 5955 ISD::CondCode Cond, 5956 DAGCombinerInfo &DCI, 5957 const SDLoc &DL) const { 5958 SmallVector<SDNode *, 5> Built; 5959 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5960 DCI, DL, Built)) { 5961 for (SDNode *N : Built) 5962 DCI.AddToWorklist(N); 5963 return Folded; 5964 } 5965 5966 return SDValue(); 5967 } 5968 5969 SDValue 5970 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5971 SDValue CompTargetNode, ISD::CondCode Cond, 5972 DAGCombinerInfo &DCI, const SDLoc &DL, 5973 SmallVectorImpl<SDNode *> &Created) const { 5974 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5975 // - D must be constant, with D = D0 * 2^K where D0 is odd 5976 // - P is the multiplicative inverse of D0 modulo 2^W 5977 // - Q = floor(((2^W) - 1) / D) 5978 // where W is the width of the common type of N and D. 5979 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5980 "Only applicable for (in)equality comparisons."); 5981 5982 SelectionDAG &DAG = DCI.DAG; 5983 5984 EVT VT = REMNode.getValueType(); 5985 EVT SVT = VT.getScalarType(); 5986 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 5987 EVT ShSVT = ShVT.getScalarType(); 5988 5989 // If MUL is unavailable, we cannot proceed in any case. 5990 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5991 return SDValue(); 5992 5993 bool ComparingWithAllZeros = true; 5994 bool AllComparisonsWithNonZerosAreTautological = true; 5995 bool HadTautologicalLanes = false; 5996 bool AllLanesAreTautological = true; 5997 bool HadEvenDivisor = false; 5998 bool AllDivisorsArePowerOfTwo = true; 5999 bool HadTautologicalInvertedLanes = false; 6000 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6001 6002 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6003 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6004 if (CDiv->isZero()) 6005 return false; 6006 6007 const APInt &D = CDiv->getAPIntValue(); 6008 const APInt &Cmp = CCmp->getAPIntValue(); 6009 6010 ComparingWithAllZeros &= Cmp.isZero(); 6011 6012 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6013 // if C2 is not less than C1, the comparison is always false. 6014 // But we will only be able to produce the comparison that will give the 6015 // opposive tautological answer. So this lane would need to be fixed up. 6016 bool TautologicalInvertedLane = D.ule(Cmp); 6017 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6018 6019 // If all lanes are tautological (either all divisors are ones, or divisor 6020 // is not greater than the constant we are comparing with), 6021 // we will prefer to avoid the fold. 6022 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6023 HadTautologicalLanes |= TautologicalLane; 6024 AllLanesAreTautological &= TautologicalLane; 6025 6026 // If we are comparing with non-zero, we need'll need to subtract said 6027 // comparison value from the LHS. But there is no point in doing that if 6028 // every lane where we are comparing with non-zero is tautological.. 6029 if (!Cmp.isZero()) 6030 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6031 6032 // Decompose D into D0 * 2^K 6033 unsigned K = D.countTrailingZeros(); 6034 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6035 APInt D0 = D.lshr(K); 6036 6037 // D is even if it has trailing zeros. 6038 HadEvenDivisor |= (K != 0); 6039 // D is a power-of-two if D0 is one. 6040 // If all divisors are power-of-two, we will prefer to avoid the fold. 6041 AllDivisorsArePowerOfTwo &= D0.isOne(); 6042 6043 // P = inv(D0, 2^W) 6044 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6045 unsigned W = D.getBitWidth(); 6046 APInt P = D0.zext(W + 1) 6047 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6048 .trunc(W); 6049 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6050 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6051 6052 // Q = floor((2^W - 1) u/ D) 6053 // R = ((2^W - 1) u% D) 6054 APInt Q, R; 6055 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6056 6057 // If we are comparing with zero, then that comparison constant is okay, 6058 // else it may need to be one less than that. 6059 if (Cmp.ugt(R)) 6060 Q -= 1; 6061 6062 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6063 "We are expecting that K is always less than all-ones for ShSVT"); 6064 6065 // If the lane is tautological the result can be constant-folded. 6066 if (TautologicalLane) { 6067 // Set P and K amount to a bogus values so we can try to splat them. 6068 P = 0; 6069 K = -1; 6070 // And ensure that comparison constant is tautological, 6071 // it will always compare true/false. 6072 Q = -1; 6073 } 6074 6075 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6076 KAmts.push_back( 6077 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6078 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6079 return true; 6080 }; 6081 6082 SDValue N = REMNode.getOperand(0); 6083 SDValue D = REMNode.getOperand(1); 6084 6085 // Collect the values from each element. 6086 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6087 return SDValue(); 6088 6089 // If all lanes are tautological, the result can be constant-folded. 6090 if (AllLanesAreTautological) 6091 return SDValue(); 6092 6093 // If this is a urem by a powers-of-two, avoid the fold since it can be 6094 // best implemented as a bit test. 6095 if (AllDivisorsArePowerOfTwo) 6096 return SDValue(); 6097 6098 SDValue PVal, KVal, QVal; 6099 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6100 if (HadTautologicalLanes) { 6101 // Try to turn PAmts into a splat, since we don't care about the values 6102 // that are currently '0'. If we can't, just keep '0'`s. 6103 turnVectorIntoSplatVector(PAmts, isNullConstant); 6104 // Try to turn KAmts into a splat, since we don't care about the values 6105 // that are currently '-1'. If we can't, change them to '0'`s. 6106 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6107 DAG.getConstant(0, DL, ShSVT)); 6108 } 6109 6110 PVal = DAG.getBuildVector(VT, DL, PAmts); 6111 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6112 QVal = DAG.getBuildVector(VT, DL, QAmts); 6113 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6114 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6115 "Expected matchBinaryPredicate to return one element for " 6116 "SPLAT_VECTORs"); 6117 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6118 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6119 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6120 } else { 6121 PVal = PAmts[0]; 6122 KVal = KAmts[0]; 6123 QVal = QAmts[0]; 6124 } 6125 6126 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6127 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6128 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6129 assert(CompTargetNode.getValueType() == N.getValueType() && 6130 "Expecting that the types on LHS and RHS of comparisons match."); 6131 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6132 } 6133 6134 // (mul N, P) 6135 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6136 Created.push_back(Op0.getNode()); 6137 6138 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6139 // divisors as a performance improvement, since rotating by 0 is a no-op. 6140 if (HadEvenDivisor) { 6141 // We need ROTR to do this. 6142 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6143 return SDValue(); 6144 // UREM: (rotr (mul N, P), K) 6145 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6146 Created.push_back(Op0.getNode()); 6147 } 6148 6149 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6150 SDValue NewCC = 6151 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6152 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6153 if (!HadTautologicalInvertedLanes) 6154 return NewCC; 6155 6156 // If any lanes previously compared always-false, the NewCC will give 6157 // always-true result for them, so we need to fixup those lanes. 6158 // Or the other way around for inequality predicate. 6159 assert(VT.isVector() && "Can/should only get here for vectors."); 6160 Created.push_back(NewCC.getNode()); 6161 6162 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6163 // if C2 is not less than C1, the comparison is always false. 6164 // But we have produced the comparison that will give the 6165 // opposive tautological answer. So these lanes would need to be fixed up. 6166 SDValue TautologicalInvertedChannels = 6167 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6168 Created.push_back(TautologicalInvertedChannels.getNode()); 6169 6170 // NOTE: we avoid letting illegal types through even if we're before legalize 6171 // ops – legalization has a hard time producing good code for this. 6172 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6173 // If we have a vector select, let's replace the comparison results in the 6174 // affected lanes with the correct tautological result. 6175 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6176 DL, SETCCVT, SETCCVT); 6177 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6178 Replacement, NewCC); 6179 } 6180 6181 // Else, we can just invert the comparison result in the appropriate lanes. 6182 // 6183 // NOTE: see the note above VSELECT above. 6184 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6185 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6186 TautologicalInvertedChannels); 6187 6188 return SDValue(); // Don't know how to lower. 6189 } 6190 6191 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6192 /// where the divisor is constant and the comparison target is zero, 6193 /// return a DAG expression that will generate the same comparison result 6194 /// using only multiplications, additions and shifts/rotations. 6195 /// Ref: "Hacker's Delight" 10-17. 6196 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6197 SDValue CompTargetNode, 6198 ISD::CondCode Cond, 6199 DAGCombinerInfo &DCI, 6200 const SDLoc &DL) const { 6201 SmallVector<SDNode *, 7> Built; 6202 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6203 DCI, DL, Built)) { 6204 assert(Built.size() <= 7 && "Max size prediction failed."); 6205 for (SDNode *N : Built) 6206 DCI.AddToWorklist(N); 6207 return Folded; 6208 } 6209 6210 return SDValue(); 6211 } 6212 6213 SDValue 6214 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6215 SDValue CompTargetNode, ISD::CondCode Cond, 6216 DAGCombinerInfo &DCI, const SDLoc &DL, 6217 SmallVectorImpl<SDNode *> &Created) const { 6218 // Fold: 6219 // (seteq/ne (srem N, D), 0) 6220 // To: 6221 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6222 // 6223 // - D must be constant, with D = D0 * 2^K where D0 is odd 6224 // - P is the multiplicative inverse of D0 modulo 2^W 6225 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6226 // - Q = floor((2 * A) / (2^K)) 6227 // where W is the width of the common type of N and D. 6228 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6229 "Only applicable for (in)equality comparisons."); 6230 6231 SelectionDAG &DAG = DCI.DAG; 6232 6233 EVT VT = REMNode.getValueType(); 6234 EVT SVT = VT.getScalarType(); 6235 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6236 EVT ShSVT = ShVT.getScalarType(); 6237 6238 // If we are after ops legalization, and MUL is unavailable, we can not 6239 // proceed. 6240 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6241 return SDValue(); 6242 6243 // TODO: Could support comparing with non-zero too. 6244 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6245 if (!CompTarget || !CompTarget->isZero()) 6246 return SDValue(); 6247 6248 bool HadIntMinDivisor = false; 6249 bool HadOneDivisor = false; 6250 bool AllDivisorsAreOnes = true; 6251 bool HadEvenDivisor = false; 6252 bool NeedToApplyOffset = false; 6253 bool AllDivisorsArePowerOfTwo = true; 6254 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6255 6256 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6257 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6258 if (C->isZero()) 6259 return false; 6260 6261 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6262 6263 // WARNING: this fold is only valid for positive divisors! 6264 APInt D = C->getAPIntValue(); 6265 if (D.isNegative()) 6266 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6267 6268 HadIntMinDivisor |= D.isMinSignedValue(); 6269 6270 // If all divisors are ones, we will prefer to avoid the fold. 6271 HadOneDivisor |= D.isOne(); 6272 AllDivisorsAreOnes &= D.isOne(); 6273 6274 // Decompose D into D0 * 2^K 6275 unsigned K = D.countTrailingZeros(); 6276 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6277 APInt D0 = D.lshr(K); 6278 6279 if (!D.isMinSignedValue()) { 6280 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6281 // we don't care about this lane in this fold, we'll special-handle it. 6282 HadEvenDivisor |= (K != 0); 6283 } 6284 6285 // D is a power-of-two if D0 is one. This includes INT_MIN. 6286 // If all divisors are power-of-two, we will prefer to avoid the fold. 6287 AllDivisorsArePowerOfTwo &= D0.isOne(); 6288 6289 // P = inv(D0, 2^W) 6290 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6291 unsigned W = D.getBitWidth(); 6292 APInt P = D0.zext(W + 1) 6293 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6294 .trunc(W); 6295 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6296 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6297 6298 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6299 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6300 A.clearLowBits(K); 6301 6302 if (!D.isMinSignedValue()) { 6303 // If divisor INT_MIN, then we don't care about this lane in this fold, 6304 // we'll special-handle it. 6305 NeedToApplyOffset |= A != 0; 6306 } 6307 6308 // Q = floor((2 * A) / (2^K)) 6309 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6310 6311 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6312 "We are expecting that A is always less than all-ones for SVT"); 6313 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6314 "We are expecting that K is always less than all-ones for ShSVT"); 6315 6316 // If the divisor is 1 the result can be constant-folded. Likewise, we 6317 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6318 if (D.isOne()) { 6319 // Set P, A and K to a bogus values so we can try to splat them. 6320 P = 0; 6321 A = -1; 6322 K = -1; 6323 6324 // x ?% 1 == 0 <--> true <--> x u<= -1 6325 Q = -1; 6326 } 6327 6328 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6329 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6330 KAmts.push_back( 6331 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6332 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6333 return true; 6334 }; 6335 6336 SDValue N = REMNode.getOperand(0); 6337 SDValue D = REMNode.getOperand(1); 6338 6339 // Collect the values from each element. 6340 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6341 return SDValue(); 6342 6343 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6344 if (AllDivisorsAreOnes) 6345 return SDValue(); 6346 6347 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6348 // since it can be best implemented as a bit test. 6349 if (AllDivisorsArePowerOfTwo) 6350 return SDValue(); 6351 6352 SDValue PVal, AVal, KVal, QVal; 6353 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6354 if (HadOneDivisor) { 6355 // Try to turn PAmts into a splat, since we don't care about the values 6356 // that are currently '0'. If we can't, just keep '0'`s. 6357 turnVectorIntoSplatVector(PAmts, isNullConstant); 6358 // Try to turn AAmts into a splat, since we don't care about the 6359 // values that are currently '-1'. If we can't, change them to '0'`s. 6360 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6361 DAG.getConstant(0, DL, SVT)); 6362 // Try to turn KAmts into a splat, since we don't care about the values 6363 // that are currently '-1'. If we can't, change them to '0'`s. 6364 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6365 DAG.getConstant(0, DL, ShSVT)); 6366 } 6367 6368 PVal = DAG.getBuildVector(VT, DL, PAmts); 6369 AVal = DAG.getBuildVector(VT, DL, AAmts); 6370 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6371 QVal = DAG.getBuildVector(VT, DL, QAmts); 6372 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6373 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6374 QAmts.size() == 1 && 6375 "Expected matchUnaryPredicate to return one element for scalable " 6376 "vectors"); 6377 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6378 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6379 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6380 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6381 } else { 6382 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6383 PVal = PAmts[0]; 6384 AVal = AAmts[0]; 6385 KVal = KAmts[0]; 6386 QVal = QAmts[0]; 6387 } 6388 6389 // (mul N, P) 6390 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6391 Created.push_back(Op0.getNode()); 6392 6393 if (NeedToApplyOffset) { 6394 // We need ADD to do this. 6395 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6396 return SDValue(); 6397 6398 // (add (mul N, P), A) 6399 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6400 Created.push_back(Op0.getNode()); 6401 } 6402 6403 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6404 // divisors as a performance improvement, since rotating by 0 is a no-op. 6405 if (HadEvenDivisor) { 6406 // We need ROTR to do this. 6407 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6408 return SDValue(); 6409 // SREM: (rotr (add (mul N, P), A), K) 6410 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6411 Created.push_back(Op0.getNode()); 6412 } 6413 6414 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6415 SDValue Fold = 6416 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6417 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6418 6419 // If we didn't have lanes with INT_MIN divisor, then we're done. 6420 if (!HadIntMinDivisor) 6421 return Fold; 6422 6423 // That fold is only valid for positive divisors. Which effectively means, 6424 // it is invalid for INT_MIN divisors. So if we have such a lane, 6425 // we must fix-up results for said lanes. 6426 assert(VT.isVector() && "Can/should only get here for vectors."); 6427 6428 // NOTE: we avoid letting illegal types through even if we're before legalize 6429 // ops – legalization has a hard time producing good code for the code that 6430 // follows. 6431 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6432 !isOperationLegalOrCustom(ISD::AND, VT) || 6433 !isOperationLegalOrCustom(Cond, VT) || 6434 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6435 return SDValue(); 6436 6437 Created.push_back(Fold.getNode()); 6438 6439 SDValue IntMin = DAG.getConstant( 6440 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6441 SDValue IntMax = DAG.getConstant( 6442 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6443 SDValue Zero = 6444 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6445 6446 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6447 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6448 Created.push_back(DivisorIsIntMin.getNode()); 6449 6450 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6451 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6452 Created.push_back(Masked.getNode()); 6453 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6454 Created.push_back(MaskedIsZero.getNode()); 6455 6456 // To produce final result we need to blend 2 vectors: 'SetCC' and 6457 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6458 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6459 // constant-folded, select can get lowered to a shuffle with constant mask. 6460 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6461 MaskedIsZero, Fold); 6462 6463 return Blended; 6464 } 6465 6466 bool TargetLowering:: 6467 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6468 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6469 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6470 "be a constant integer"); 6471 return true; 6472 } 6473 6474 return false; 6475 } 6476 6477 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6478 const DenormalMode &Mode) const { 6479 SDLoc DL(Op); 6480 EVT VT = Op.getValueType(); 6481 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6482 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6483 // Testing it with denormal inputs to avoid wrong estimate. 6484 if (Mode.Input == DenormalMode::IEEE) { 6485 // This is specifically a check for the handling of denormal inputs, 6486 // not the result. 6487 6488 // Test = fabs(X) < SmallestNormal 6489 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6490 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6491 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6492 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6493 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6494 } 6495 // Test = X == 0.0 6496 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6497 } 6498 6499 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6500 bool LegalOps, bool OptForSize, 6501 NegatibleCost &Cost, 6502 unsigned Depth) const { 6503 // fneg is removable even if it has multiple uses. 6504 if (Op.getOpcode() == ISD::FNEG) { 6505 Cost = NegatibleCost::Cheaper; 6506 return Op.getOperand(0); 6507 } 6508 6509 // Don't recurse exponentially. 6510 if (Depth > SelectionDAG::MaxRecursionDepth) 6511 return SDValue(); 6512 6513 // Pre-increment recursion depth for use in recursive calls. 6514 ++Depth; 6515 const SDNodeFlags Flags = Op->getFlags(); 6516 const TargetOptions &Options = DAG.getTarget().Options; 6517 EVT VT = Op.getValueType(); 6518 unsigned Opcode = Op.getOpcode(); 6519 6520 // Don't allow anything with multiple uses unless we know it is free. 6521 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6522 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6523 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6524 if (!IsFreeExtend) 6525 return SDValue(); 6526 } 6527 6528 auto RemoveDeadNode = [&](SDValue N) { 6529 if (N && N.getNode()->use_empty()) 6530 DAG.RemoveDeadNode(N.getNode()); 6531 }; 6532 6533 SDLoc DL(Op); 6534 6535 // Because getNegatedExpression can delete nodes we need a handle to keep 6536 // temporary nodes alive in case the recursion manages to create an identical 6537 // node. 6538 std::list<HandleSDNode> Handles; 6539 6540 switch (Opcode) { 6541 case ISD::ConstantFP: { 6542 // Don't invert constant FP values after legalization unless the target says 6543 // the negated constant is legal. 6544 bool IsOpLegal = 6545 isOperationLegal(ISD::ConstantFP, VT) || 6546 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6547 OptForSize); 6548 6549 if (LegalOps && !IsOpLegal) 6550 break; 6551 6552 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6553 V.changeSign(); 6554 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6555 6556 // If we already have the use of the negated floating constant, it is free 6557 // to negate it even it has multiple uses. 6558 if (!Op.hasOneUse() && CFP.use_empty()) 6559 break; 6560 Cost = NegatibleCost::Neutral; 6561 return CFP; 6562 } 6563 case ISD::BUILD_VECTOR: { 6564 // Only permit BUILD_VECTOR of constants. 6565 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6566 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6567 })) 6568 break; 6569 6570 bool IsOpLegal = 6571 (isOperationLegal(ISD::ConstantFP, VT) && 6572 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6573 llvm::all_of(Op->op_values(), [&](SDValue N) { 6574 return N.isUndef() || 6575 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6576 OptForSize); 6577 }); 6578 6579 if (LegalOps && !IsOpLegal) 6580 break; 6581 6582 SmallVector<SDValue, 4> Ops; 6583 for (SDValue C : Op->op_values()) { 6584 if (C.isUndef()) { 6585 Ops.push_back(C); 6586 continue; 6587 } 6588 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6589 V.changeSign(); 6590 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6591 } 6592 Cost = NegatibleCost::Neutral; 6593 return DAG.getBuildVector(VT, DL, Ops); 6594 } 6595 case ISD::FADD: { 6596 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6597 break; 6598 6599 // After operation legalization, it might not be legal to create new FSUBs. 6600 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6601 break; 6602 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6603 6604 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6605 NegatibleCost CostX = NegatibleCost::Expensive; 6606 SDValue NegX = 6607 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6608 // Prevent this node from being deleted by the next call. 6609 if (NegX) 6610 Handles.emplace_back(NegX); 6611 6612 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6613 NegatibleCost CostY = NegatibleCost::Expensive; 6614 SDValue NegY = 6615 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6616 6617 // We're done with the handles. 6618 Handles.clear(); 6619 6620 // Negate the X if its cost is less or equal than Y. 6621 if (NegX && (CostX <= CostY)) { 6622 Cost = CostX; 6623 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6624 if (NegY != N) 6625 RemoveDeadNode(NegY); 6626 return N; 6627 } 6628 6629 // Negate the Y if it is not expensive. 6630 if (NegY) { 6631 Cost = CostY; 6632 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6633 if (NegX != N) 6634 RemoveDeadNode(NegX); 6635 return N; 6636 } 6637 break; 6638 } 6639 case ISD::FSUB: { 6640 // We can't turn -(A-B) into B-A when we honor signed zeros. 6641 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6642 break; 6643 6644 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6645 // fold (fneg (fsub 0, Y)) -> Y 6646 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6647 if (C->isZero()) { 6648 Cost = NegatibleCost::Cheaper; 6649 return Y; 6650 } 6651 6652 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6653 Cost = NegatibleCost::Neutral; 6654 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6655 } 6656 case ISD::FMUL: 6657 case ISD::FDIV: { 6658 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6659 6660 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6661 NegatibleCost CostX = NegatibleCost::Expensive; 6662 SDValue NegX = 6663 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6664 // Prevent this node from being deleted by the next call. 6665 if (NegX) 6666 Handles.emplace_back(NegX); 6667 6668 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6669 NegatibleCost CostY = NegatibleCost::Expensive; 6670 SDValue NegY = 6671 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6672 6673 // We're done with the handles. 6674 Handles.clear(); 6675 6676 // Negate the X if its cost is less or equal than Y. 6677 if (NegX && (CostX <= CostY)) { 6678 Cost = CostX; 6679 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6680 if (NegY != N) 6681 RemoveDeadNode(NegY); 6682 return N; 6683 } 6684 6685 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6686 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6687 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6688 break; 6689 6690 // Negate the Y if it is not expensive. 6691 if (NegY) { 6692 Cost = CostY; 6693 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6694 if (NegX != N) 6695 RemoveDeadNode(NegX); 6696 return N; 6697 } 6698 break; 6699 } 6700 case ISD::FMA: 6701 case ISD::FMAD: { 6702 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6703 break; 6704 6705 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6706 NegatibleCost CostZ = NegatibleCost::Expensive; 6707 SDValue NegZ = 6708 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6709 // Give up if fail to negate the Z. 6710 if (!NegZ) 6711 break; 6712 6713 // Prevent this node from being deleted by the next two calls. 6714 Handles.emplace_back(NegZ); 6715 6716 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6717 NegatibleCost CostX = NegatibleCost::Expensive; 6718 SDValue NegX = 6719 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6720 // Prevent this node from being deleted by the next call. 6721 if (NegX) 6722 Handles.emplace_back(NegX); 6723 6724 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6725 NegatibleCost CostY = NegatibleCost::Expensive; 6726 SDValue NegY = 6727 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6728 6729 // We're done with the handles. 6730 Handles.clear(); 6731 6732 // Negate the X if its cost is less or equal than Y. 6733 if (NegX && (CostX <= CostY)) { 6734 Cost = std::min(CostX, CostZ); 6735 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6736 if (NegY != N) 6737 RemoveDeadNode(NegY); 6738 return N; 6739 } 6740 6741 // Negate the Y if it is not expensive. 6742 if (NegY) { 6743 Cost = std::min(CostY, CostZ); 6744 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6745 if (NegX != N) 6746 RemoveDeadNode(NegX); 6747 return N; 6748 } 6749 break; 6750 } 6751 6752 case ISD::FP_EXTEND: 6753 case ISD::FSIN: 6754 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6755 OptForSize, Cost, Depth)) 6756 return DAG.getNode(Opcode, DL, VT, NegV); 6757 break; 6758 case ISD::FP_ROUND: 6759 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6760 OptForSize, Cost, Depth)) 6761 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6762 break; 6763 } 6764 6765 return SDValue(); 6766 } 6767 6768 //===----------------------------------------------------------------------===// 6769 // Legalization Utilities 6770 //===----------------------------------------------------------------------===// 6771 6772 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6773 SDValue LHS, SDValue RHS, 6774 SmallVectorImpl<SDValue> &Result, 6775 EVT HiLoVT, SelectionDAG &DAG, 6776 MulExpansionKind Kind, SDValue LL, 6777 SDValue LH, SDValue RL, SDValue RH) const { 6778 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6779 Opcode == ISD::SMUL_LOHI); 6780 6781 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6782 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6783 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6784 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6785 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6786 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6787 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6788 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6789 6790 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6791 return false; 6792 6793 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6794 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6795 6796 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6797 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6798 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6799 6800 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6801 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6802 bool Signed) -> bool { 6803 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6804 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6805 Hi = SDValue(Lo.getNode(), 1); 6806 return true; 6807 } 6808 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6809 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6810 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6811 return true; 6812 } 6813 return false; 6814 }; 6815 6816 SDValue Lo, Hi; 6817 6818 if (!LL.getNode() && !RL.getNode() && 6819 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6820 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6821 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6822 } 6823 6824 if (!LL.getNode()) 6825 return false; 6826 6827 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6828 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6829 DAG.MaskedValueIsZero(RHS, HighMask)) { 6830 // The inputs are both zero-extended. 6831 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6832 Result.push_back(Lo); 6833 Result.push_back(Hi); 6834 if (Opcode != ISD::MUL) { 6835 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6836 Result.push_back(Zero); 6837 Result.push_back(Zero); 6838 } 6839 return true; 6840 } 6841 } 6842 6843 if (!VT.isVector() && Opcode == ISD::MUL && 6844 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6845 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6846 // The input values are both sign-extended. 6847 // TODO non-MUL case? 6848 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6849 Result.push_back(Lo); 6850 Result.push_back(Hi); 6851 return true; 6852 } 6853 } 6854 6855 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6856 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6857 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6858 6859 if (!LH.getNode() && !RH.getNode() && 6860 isOperationLegalOrCustom(ISD::SRL, VT) && 6861 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6862 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6863 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6864 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6865 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6866 } 6867 6868 if (!LH.getNode()) 6869 return false; 6870 6871 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6872 return false; 6873 6874 Result.push_back(Lo); 6875 6876 if (Opcode == ISD::MUL) { 6877 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6878 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6879 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6880 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6881 Result.push_back(Hi); 6882 return true; 6883 } 6884 6885 // Compute the full width result. 6886 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6887 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6888 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6889 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6890 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6891 }; 6892 6893 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6894 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6895 return false; 6896 6897 // This is effectively the add part of a multiply-add of half-sized operands, 6898 // so it cannot overflow. 6899 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6900 6901 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6902 return false; 6903 6904 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6905 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6906 6907 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6908 isOperationLegalOrCustom(ISD::ADDE, VT)); 6909 if (UseGlue) 6910 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6911 Merge(Lo, Hi)); 6912 else 6913 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6914 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6915 6916 SDValue Carry = Next.getValue(1); 6917 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6918 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6919 6920 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6921 return false; 6922 6923 if (UseGlue) 6924 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6925 Carry); 6926 else 6927 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6928 Zero, Carry); 6929 6930 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6931 6932 if (Opcode == ISD::SMUL_LOHI) { 6933 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6934 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6935 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6936 6937 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6938 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6939 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6940 } 6941 6942 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6943 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6944 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6945 return true; 6946 } 6947 6948 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6949 SelectionDAG &DAG, MulExpansionKind Kind, 6950 SDValue LL, SDValue LH, SDValue RL, 6951 SDValue RH) const { 6952 SmallVector<SDValue, 2> Result; 6953 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6954 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6955 DAG, Kind, LL, LH, RL, RH); 6956 if (Ok) { 6957 assert(Result.size() == 2); 6958 Lo = Result[0]; 6959 Hi = Result[1]; 6960 } 6961 return Ok; 6962 } 6963 6964 // Check that (every element of) Z is undef or not an exact multiple of BW. 6965 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6966 return ISD::matchUnaryPredicate( 6967 Z, 6968 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6969 true); 6970 } 6971 6972 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 6973 SelectionDAG &DAG) const { 6974 EVT VT = Node->getValueType(0); 6975 6976 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6977 !isOperationLegalOrCustom(ISD::SRL, VT) || 6978 !isOperationLegalOrCustom(ISD::SUB, VT) || 6979 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6980 return SDValue(); 6981 6982 SDValue X = Node->getOperand(0); 6983 SDValue Y = Node->getOperand(1); 6984 SDValue Z = Node->getOperand(2); 6985 6986 unsigned BW = VT.getScalarSizeInBits(); 6987 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6988 SDLoc DL(SDValue(Node, 0)); 6989 6990 EVT ShVT = Z.getValueType(); 6991 6992 // If a funnel shift in the other direction is more supported, use it. 6993 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6994 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6995 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6996 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6997 // fshl X, Y, Z -> fshr X, Y, -Z 6998 // fshr X, Y, Z -> fshl X, Y, -Z 6999 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7000 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7001 } else { 7002 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7003 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7004 SDValue One = DAG.getConstant(1, DL, ShVT); 7005 if (IsFSHL) { 7006 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7007 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7008 } else { 7009 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7010 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7011 } 7012 Z = DAG.getNOT(DL, Z, ShVT); 7013 } 7014 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7015 } 7016 7017 SDValue ShX, ShY; 7018 SDValue ShAmt, InvShAmt; 7019 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7020 // fshl: X << C | Y >> (BW - C) 7021 // fshr: X << (BW - C) | Y >> C 7022 // where C = Z % BW is not zero 7023 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7024 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7025 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7026 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7027 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7028 } else { 7029 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7030 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7031 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7032 if (isPowerOf2_32(BW)) { 7033 // Z % BW -> Z & (BW - 1) 7034 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7035 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7036 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7037 } else { 7038 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7039 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7040 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7041 } 7042 7043 SDValue One = DAG.getConstant(1, DL, ShVT); 7044 if (IsFSHL) { 7045 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7046 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7047 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7048 } else { 7049 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7050 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7051 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7052 } 7053 } 7054 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7055 } 7056 7057 // TODO: Merge with expandFunnelShift. 7058 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7059 SelectionDAG &DAG) const { 7060 EVT VT = Node->getValueType(0); 7061 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7062 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7063 SDValue Op0 = Node->getOperand(0); 7064 SDValue Op1 = Node->getOperand(1); 7065 SDLoc DL(SDValue(Node, 0)); 7066 7067 EVT ShVT = Op1.getValueType(); 7068 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7069 7070 // If a rotate in the other direction is more supported, use it. 7071 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7072 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7073 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7074 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7075 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7076 } 7077 7078 if (!AllowVectorOps && VT.isVector() && 7079 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7080 !isOperationLegalOrCustom(ISD::SRL, VT) || 7081 !isOperationLegalOrCustom(ISD::SUB, VT) || 7082 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7083 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7084 return SDValue(); 7085 7086 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7087 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7088 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7089 SDValue ShVal; 7090 SDValue HsVal; 7091 if (isPowerOf2_32(EltSizeInBits)) { 7092 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7093 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7094 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7095 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7096 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7097 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7098 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7099 } else { 7100 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7101 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7102 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7103 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7104 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7105 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7106 SDValue One = DAG.getConstant(1, DL, ShVT); 7107 HsVal = 7108 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7109 } 7110 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7111 } 7112 7113 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7114 SelectionDAG &DAG) const { 7115 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7116 EVT VT = Node->getValueType(0); 7117 unsigned VTBits = VT.getScalarSizeInBits(); 7118 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7119 7120 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7121 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7122 SDValue ShOpLo = Node->getOperand(0); 7123 SDValue ShOpHi = Node->getOperand(1); 7124 SDValue ShAmt = Node->getOperand(2); 7125 EVT ShAmtVT = ShAmt.getValueType(); 7126 EVT ShAmtCCVT = 7127 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7128 SDLoc dl(Node); 7129 7130 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7131 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7132 // away during isel. 7133 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7134 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7135 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7136 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7137 : DAG.getConstant(0, dl, VT); 7138 7139 SDValue Tmp2, Tmp3; 7140 if (IsSHL) { 7141 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7142 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7143 } else { 7144 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7145 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7146 } 7147 7148 // If the shift amount is larger or equal than the width of a part we don't 7149 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7150 // values for large shift amounts. 7151 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7152 DAG.getConstant(VTBits, dl, ShAmtVT)); 7153 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7154 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7155 7156 if (IsSHL) { 7157 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7158 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7159 } else { 7160 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7161 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7162 } 7163 } 7164 7165 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7166 SelectionDAG &DAG) const { 7167 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7168 SDValue Src = Node->getOperand(OpNo); 7169 EVT SrcVT = Src.getValueType(); 7170 EVT DstVT = Node->getValueType(0); 7171 SDLoc dl(SDValue(Node, 0)); 7172 7173 // FIXME: Only f32 to i64 conversions are supported. 7174 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7175 return false; 7176 7177 if (Node->isStrictFPOpcode()) 7178 // When a NaN is converted to an integer a trap is allowed. We can't 7179 // use this expansion here because it would eliminate that trap. Other 7180 // traps are also allowed and cannot be eliminated. See 7181 // IEEE 754-2008 sec 5.8. 7182 return false; 7183 7184 // Expand f32 -> i64 conversion 7185 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7186 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7187 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7188 EVT IntVT = SrcVT.changeTypeToInteger(); 7189 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7190 7191 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7192 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7193 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7194 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7195 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7196 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7197 7198 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7199 7200 SDValue ExponentBits = DAG.getNode( 7201 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7202 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7203 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7204 7205 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7206 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7207 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7208 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7209 7210 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7211 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7212 DAG.getConstant(0x00800000, dl, IntVT)); 7213 7214 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7215 7216 R = DAG.getSelectCC( 7217 dl, Exponent, ExponentLoBit, 7218 DAG.getNode(ISD::SHL, dl, DstVT, R, 7219 DAG.getZExtOrTrunc( 7220 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7221 dl, IntShVT)), 7222 DAG.getNode(ISD::SRL, dl, DstVT, R, 7223 DAG.getZExtOrTrunc( 7224 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7225 dl, IntShVT)), 7226 ISD::SETGT); 7227 7228 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7229 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7230 7231 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7232 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7233 return true; 7234 } 7235 7236 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7237 SDValue &Chain, 7238 SelectionDAG &DAG) const { 7239 SDLoc dl(SDValue(Node, 0)); 7240 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7241 SDValue Src = Node->getOperand(OpNo); 7242 7243 EVT SrcVT = Src.getValueType(); 7244 EVT DstVT = Node->getValueType(0); 7245 EVT SetCCVT = 7246 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7247 EVT DstSetCCVT = 7248 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7249 7250 // Only expand vector types if we have the appropriate vector bit operations. 7251 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7252 ISD::FP_TO_SINT; 7253 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7254 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7255 return false; 7256 7257 // If the maximum float value is smaller then the signed integer range, 7258 // the destination signmask can't be represented by the float, so we can 7259 // just use FP_TO_SINT directly. 7260 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7261 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7262 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7263 if (APFloat::opOverflow & 7264 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7265 if (Node->isStrictFPOpcode()) { 7266 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7267 { Node->getOperand(0), Src }); 7268 Chain = Result.getValue(1); 7269 } else 7270 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7271 return true; 7272 } 7273 7274 // Don't expand it if there isn't cheap fsub instruction. 7275 if (!isOperationLegalOrCustom( 7276 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7277 return false; 7278 7279 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7280 SDValue Sel; 7281 7282 if (Node->isStrictFPOpcode()) { 7283 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7284 Node->getOperand(0), /*IsSignaling*/ true); 7285 Chain = Sel.getValue(1); 7286 } else { 7287 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7288 } 7289 7290 bool Strict = Node->isStrictFPOpcode() || 7291 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7292 7293 if (Strict) { 7294 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7295 // signmask then offset (the result of which should be fully representable). 7296 // Sel = Src < 0x8000000000000000 7297 // FltOfs = select Sel, 0, 0x8000000000000000 7298 // IntOfs = select Sel, 0, 0x8000000000000000 7299 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7300 7301 // TODO: Should any fast-math-flags be set for the FSUB? 7302 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7303 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7304 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7305 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7306 DAG.getConstant(0, dl, DstVT), 7307 DAG.getConstant(SignMask, dl, DstVT)); 7308 SDValue SInt; 7309 if (Node->isStrictFPOpcode()) { 7310 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7311 { Chain, Src, FltOfs }); 7312 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7313 { Val.getValue(1), Val }); 7314 Chain = SInt.getValue(1); 7315 } else { 7316 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7317 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7318 } 7319 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7320 } else { 7321 // Expand based on maximum range of FP_TO_SINT: 7322 // True = fp_to_sint(Src) 7323 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7324 // Result = select (Src < 0x8000000000000000), True, False 7325 7326 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7327 // TODO: Should any fast-math-flags be set for the FSUB? 7328 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7329 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7330 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7331 DAG.getConstant(SignMask, dl, DstVT)); 7332 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7333 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7334 } 7335 return true; 7336 } 7337 7338 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7339 SDValue &Chain, 7340 SelectionDAG &DAG) const { 7341 // This transform is not correct for converting 0 when rounding mode is set 7342 // to round toward negative infinity which will produce -0.0. So disable under 7343 // strictfp. 7344 if (Node->isStrictFPOpcode()) 7345 return false; 7346 7347 SDValue Src = Node->getOperand(0); 7348 EVT SrcVT = Src.getValueType(); 7349 EVT DstVT = Node->getValueType(0); 7350 7351 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7352 return false; 7353 7354 // Only expand vector types if we have the appropriate vector bit operations. 7355 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7356 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7357 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7358 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7359 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7360 return false; 7361 7362 SDLoc dl(SDValue(Node, 0)); 7363 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7364 7365 // Implementation of unsigned i64 to f64 following the algorithm in 7366 // __floatundidf in compiler_rt. This implementation performs rounding 7367 // correctly in all rounding modes with the exception of converting 0 7368 // when rounding toward negative infinity. In that case the fsub will produce 7369 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7370 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7371 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7372 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7373 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7374 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7375 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7376 7377 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7378 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7379 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7380 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7381 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7382 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7383 SDValue HiSub = 7384 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7385 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7386 return true; 7387 } 7388 7389 SDValue 7390 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7391 SelectionDAG &DAG) const { 7392 unsigned Opcode = Node->getOpcode(); 7393 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7394 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7395 "Wrong opcode"); 7396 7397 if (Node->getFlags().hasNoNaNs()) { 7398 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7399 SDValue Op1 = Node->getOperand(0); 7400 SDValue Op2 = Node->getOperand(1); 7401 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7402 // Copy FMF flags, but always set the no-signed-zeros flag 7403 // as this is implied by the FMINNUM/FMAXNUM semantics. 7404 SDNodeFlags Flags = Node->getFlags(); 7405 Flags.setNoSignedZeros(true); 7406 SelCC->setFlags(Flags); 7407 return SelCC; 7408 } 7409 7410 return SDValue(); 7411 } 7412 7413 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7414 SelectionDAG &DAG) const { 7415 SDLoc dl(Node); 7416 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7417 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7418 EVT VT = Node->getValueType(0); 7419 7420 if (VT.isScalableVector()) 7421 report_fatal_error( 7422 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7423 7424 if (isOperationLegalOrCustom(NewOp, VT)) { 7425 SDValue Quiet0 = Node->getOperand(0); 7426 SDValue Quiet1 = Node->getOperand(1); 7427 7428 if (!Node->getFlags().hasNoNaNs()) { 7429 // Insert canonicalizes if it's possible we need to quiet to get correct 7430 // sNaN behavior. 7431 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7432 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7433 Node->getFlags()); 7434 } 7435 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7436 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7437 Node->getFlags()); 7438 } 7439 } 7440 7441 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7442 } 7443 7444 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7445 // instead if there are no NaNs. 7446 if (Node->getFlags().hasNoNaNs()) { 7447 unsigned IEEE2018Op = 7448 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7449 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7450 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7451 Node->getOperand(1), Node->getFlags()); 7452 } 7453 } 7454 7455 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7456 return SelCC; 7457 7458 return SDValue(); 7459 } 7460 7461 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7462 unsigned Test, SDNodeFlags Flags, 7463 const SDLoc &DL, 7464 SelectionDAG &DAG) const { 7465 EVT OperandVT = Op.getValueType(); 7466 assert(OperandVT.isFloatingPoint()); 7467 7468 // Degenerated cases. 7469 if (Test == 0) 7470 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7471 if ((Test & fcAllFlags) == fcAllFlags) 7472 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7473 7474 // PPC double double is a pair of doubles, of which the higher part determines 7475 // the value class. 7476 if (OperandVT == MVT::ppcf128) { 7477 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7478 DAG.getConstant(1, DL, MVT::i32)); 7479 OperandVT = MVT::f64; 7480 } 7481 7482 // Some checks may be represented as inversion of simpler check, for example 7483 // "inf|normal|subnormal|zero" => !"nan". 7484 bool IsInverted = false; 7485 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7486 IsInverted = true; 7487 Test = InvertedCheck; 7488 } 7489 7490 // Floating-point type properties. 7491 EVT ScalarFloatVT = OperandVT.getScalarType(); 7492 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7493 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7494 bool IsF80 = (ScalarFloatVT == MVT::f80); 7495 7496 // Some checks can be implemented using float comparisons, if floating point 7497 // exceptions are ignored. 7498 if (Flags.hasNoFPExcept() && 7499 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7500 if (Test == fcZero) 7501 return DAG.getSetCC(DL, ResultVT, Op, 7502 DAG.getConstantFP(0.0, DL, OperandVT), 7503 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7504 if (Test == fcNan) 7505 return DAG.getSetCC(DL, ResultVT, Op, Op, 7506 IsInverted ? ISD::SETO : ISD::SETUO); 7507 } 7508 7509 // In the general case use integer operations. 7510 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7511 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7512 if (OperandVT.isVector()) 7513 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7514 OperandVT.getVectorElementCount()); 7515 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7516 7517 // Various masks. 7518 APInt SignBit = APInt::getSignMask(BitSize); 7519 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7520 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7521 const unsigned ExplicitIntBitInF80 = 63; 7522 APInt ExpMask = Inf; 7523 if (IsF80) 7524 ExpMask.clearBit(ExplicitIntBitInF80); 7525 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7526 APInt QNaNBitMask = 7527 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7528 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7529 7530 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7531 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7532 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7533 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7534 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7535 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7536 7537 SDValue Res; 7538 const auto appendResult = [&](SDValue PartialRes) { 7539 if (PartialRes) { 7540 if (Res) 7541 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7542 else 7543 Res = PartialRes; 7544 } 7545 }; 7546 7547 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7548 const auto getIntBitIsSet = [&]() -> SDValue { 7549 if (!IntBitIsSetV) { 7550 APInt IntBitMask(BitSize, 0); 7551 IntBitMask.setBit(ExplicitIntBitInF80); 7552 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7553 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7554 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7555 } 7556 return IntBitIsSetV; 7557 }; 7558 7559 // Split the value into sign bit and absolute value. 7560 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7561 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7562 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7563 7564 // Tests that involve more than one class should be processed first. 7565 SDValue PartialRes; 7566 7567 if (IsF80) 7568 ; // Detect finite numbers of f80 by checking individual classes because 7569 // they have different settings of the explicit integer bit. 7570 else if ((Test & fcFinite) == fcFinite) { 7571 // finite(V) ==> abs(V) < exp_mask 7572 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7573 Test &= ~fcFinite; 7574 } else if ((Test & fcFinite) == fcPosFinite) { 7575 // finite(V) && V > 0 ==> V < exp_mask 7576 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7577 Test &= ~fcPosFinite; 7578 } else if ((Test & fcFinite) == fcNegFinite) { 7579 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7580 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7581 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7582 Test &= ~fcNegFinite; 7583 } 7584 appendResult(PartialRes); 7585 7586 // Check for individual classes. 7587 7588 if (unsigned PartialCheck = Test & fcZero) { 7589 if (PartialCheck == fcPosZero) 7590 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7591 else if (PartialCheck == fcZero) 7592 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7593 else // ISD::fcNegZero 7594 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7595 appendResult(PartialRes); 7596 } 7597 7598 if (unsigned PartialCheck = Test & fcInf) { 7599 if (PartialCheck == fcPosInf) 7600 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7601 else if (PartialCheck == fcInf) 7602 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7603 else { // ISD::fcNegInf 7604 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7605 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7606 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7607 } 7608 appendResult(PartialRes); 7609 } 7610 7611 if (unsigned PartialCheck = Test & fcNan) { 7612 APInt InfWithQnanBit = Inf | QNaNBitMask; 7613 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7614 if (PartialCheck == fcNan) { 7615 // isnan(V) ==> abs(V) > int(inf) 7616 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7617 if (IsF80) { 7618 // Recognize unsupported values as NaNs for compatibility with glibc. 7619 // In them (exp(V)==0) == int_bit. 7620 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7621 SDValue ExpIsZero = 7622 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7623 SDValue IsPseudo = 7624 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7625 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7626 } 7627 } else if (PartialCheck == fcQNan) { 7628 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7629 PartialRes = 7630 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7631 } else { // ISD::fcSNan 7632 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7633 // abs(V) < (unsigned(Inf) | quiet_bit) 7634 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7635 SDValue IsNotQnan = 7636 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7637 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7638 } 7639 appendResult(PartialRes); 7640 } 7641 7642 if (unsigned PartialCheck = Test & fcSubnormal) { 7643 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7644 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7645 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7646 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7647 SDValue VMinusOneV = 7648 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7649 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7650 if (PartialCheck == fcNegSubnormal) 7651 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7652 appendResult(PartialRes); 7653 } 7654 7655 if (unsigned PartialCheck = Test & fcNormal) { 7656 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7657 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7658 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7659 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7660 APInt ExpLimit = ExpMask - ExpLSB; 7661 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7662 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7663 if (PartialCheck == fcNegNormal) 7664 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7665 else if (PartialCheck == fcPosNormal) { 7666 SDValue PosSignV = 7667 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7668 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7669 } 7670 if (IsF80) 7671 PartialRes = 7672 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7673 appendResult(PartialRes); 7674 } 7675 7676 if (!Res) 7677 return DAG.getConstant(IsInverted, DL, ResultVT); 7678 if (IsInverted) 7679 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7680 return Res; 7681 } 7682 7683 // Only expand vector types if we have the appropriate vector bit operations. 7684 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7685 assert(VT.isVector() && "Expected vector type"); 7686 unsigned Len = VT.getScalarSizeInBits(); 7687 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7688 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7689 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7690 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7691 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7692 } 7693 7694 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7695 SDLoc dl(Node); 7696 EVT VT = Node->getValueType(0); 7697 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7698 SDValue Op = Node->getOperand(0); 7699 unsigned Len = VT.getScalarSizeInBits(); 7700 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7701 7702 // TODO: Add support for irregular type lengths. 7703 if (!(Len <= 128 && Len % 8 == 0)) 7704 return SDValue(); 7705 7706 // Only expand vector types if we have the appropriate vector bit operations. 7707 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7708 return SDValue(); 7709 7710 // This is the "best" algorithm from 7711 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7712 SDValue Mask55 = 7713 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7714 SDValue Mask33 = 7715 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7716 SDValue Mask0F = 7717 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7718 7719 // v = v - ((v >> 1) & 0x55555555...) 7720 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7721 DAG.getNode(ISD::AND, dl, VT, 7722 DAG.getNode(ISD::SRL, dl, VT, Op, 7723 DAG.getConstant(1, dl, ShVT)), 7724 Mask55)); 7725 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7726 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7727 DAG.getNode(ISD::AND, dl, VT, 7728 DAG.getNode(ISD::SRL, dl, VT, Op, 7729 DAG.getConstant(2, dl, ShVT)), 7730 Mask33)); 7731 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7732 Op = DAG.getNode(ISD::AND, dl, VT, 7733 DAG.getNode(ISD::ADD, dl, VT, Op, 7734 DAG.getNode(ISD::SRL, dl, VT, Op, 7735 DAG.getConstant(4, dl, ShVT))), 7736 Mask0F); 7737 7738 if (Len <= 8) 7739 return Op; 7740 7741 // Avoid the multiply if we only have 2 bytes to add. 7742 // TODO: Only doing this for scalars because vectors weren't as obviously 7743 // improved. 7744 if (Len == 16 && !VT.isVector()) { 7745 // v = (v + (v >> 8)) & 0x00FF; 7746 return DAG.getNode(ISD::AND, dl, VT, 7747 DAG.getNode(ISD::ADD, dl, VT, Op, 7748 DAG.getNode(ISD::SRL, dl, VT, Op, 7749 DAG.getConstant(8, dl, ShVT))), 7750 DAG.getConstant(0xFF, dl, VT)); 7751 } 7752 7753 // v = (v * 0x01010101...) >> (Len - 8) 7754 SDValue Mask01 = 7755 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7756 return DAG.getNode(ISD::SRL, dl, VT, 7757 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7758 DAG.getConstant(Len - 8, dl, ShVT)); 7759 } 7760 7761 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7762 SDLoc dl(Node); 7763 EVT VT = Node->getValueType(0); 7764 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7765 SDValue Op = Node->getOperand(0); 7766 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7767 7768 // If the non-ZERO_UNDEF version is supported we can use that instead. 7769 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7770 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7771 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7772 7773 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7774 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7775 EVT SetCCVT = 7776 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7777 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7778 SDValue Zero = DAG.getConstant(0, dl, VT); 7779 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7780 return DAG.getSelect(dl, VT, SrcIsZero, 7781 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7782 } 7783 7784 // Only expand vector types if we have the appropriate vector bit operations. 7785 // This includes the operations needed to expand CTPOP if it isn't supported. 7786 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7787 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7788 !canExpandVectorCTPOP(*this, VT)) || 7789 !isOperationLegalOrCustom(ISD::SRL, VT) || 7790 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7791 return SDValue(); 7792 7793 // for now, we do this: 7794 // x = x | (x >> 1); 7795 // x = x | (x >> 2); 7796 // ... 7797 // x = x | (x >>16); 7798 // x = x | (x >>32); // for 64-bit input 7799 // return popcount(~x); 7800 // 7801 // Ref: "Hacker's Delight" by Henry Warren 7802 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 7803 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7804 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7805 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7806 } 7807 Op = DAG.getNOT(dl, Op, VT); 7808 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7809 } 7810 7811 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7812 SDLoc dl(Node); 7813 EVT VT = Node->getValueType(0); 7814 SDValue Op = Node->getOperand(0); 7815 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7816 7817 // If the non-ZERO_UNDEF version is supported we can use that instead. 7818 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7819 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7820 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7821 7822 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7823 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7824 EVT SetCCVT = 7825 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7826 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7827 SDValue Zero = DAG.getConstant(0, dl, VT); 7828 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7829 return DAG.getSelect(dl, VT, SrcIsZero, 7830 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7831 } 7832 7833 // Only expand vector types if we have the appropriate vector bit operations. 7834 // This includes the operations needed to expand CTPOP if it isn't supported. 7835 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7836 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7837 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7838 !canExpandVectorCTPOP(*this, VT)) || 7839 !isOperationLegalOrCustom(ISD::SUB, VT) || 7840 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7841 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7842 return SDValue(); 7843 7844 // for now, we use: { return popcount(~x & (x - 1)); } 7845 // unless the target has ctlz but not ctpop, in which case we use: 7846 // { return 32 - nlz(~x & (x-1)); } 7847 // Ref: "Hacker's Delight" by Henry Warren 7848 SDValue Tmp = DAG.getNode( 7849 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7850 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7851 7852 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7853 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7854 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7855 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7856 } 7857 7858 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7859 } 7860 7861 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7862 bool IsNegative) const { 7863 SDLoc dl(N); 7864 EVT VT = N->getValueType(0); 7865 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7866 SDValue Op = N->getOperand(0); 7867 7868 // abs(x) -> smax(x,sub(0,x)) 7869 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7870 isOperationLegal(ISD::SMAX, VT)) { 7871 SDValue Zero = DAG.getConstant(0, dl, VT); 7872 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7873 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7874 } 7875 7876 // abs(x) -> umin(x,sub(0,x)) 7877 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7878 isOperationLegal(ISD::UMIN, VT)) { 7879 SDValue Zero = DAG.getConstant(0, dl, VT); 7880 Op = DAG.getFreeze(Op); 7881 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7882 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7883 } 7884 7885 // 0 - abs(x) -> smin(x, sub(0,x)) 7886 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7887 isOperationLegal(ISD::SMIN, VT)) { 7888 Op = DAG.getFreeze(Op); 7889 SDValue Zero = DAG.getConstant(0, dl, VT); 7890 return DAG.getNode(ISD::SMIN, dl, VT, Op, 7891 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7892 } 7893 7894 // Only expand vector types if we have the appropriate vector operations. 7895 if (VT.isVector() && 7896 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7897 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7898 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7899 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7900 return SDValue(); 7901 7902 Op = DAG.getFreeze(Op); 7903 SDValue Shift = 7904 DAG.getNode(ISD::SRA, dl, VT, Op, 7905 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7906 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7907 7908 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 7909 if (!IsNegative) 7910 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 7911 7912 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7913 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7914 } 7915 7916 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7917 SDLoc dl(N); 7918 EVT VT = N->getValueType(0); 7919 SDValue Op = N->getOperand(0); 7920 7921 if (!VT.isSimple()) 7922 return SDValue(); 7923 7924 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7925 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7926 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7927 default: 7928 return SDValue(); 7929 case MVT::i16: 7930 // Use a rotate by 8. This can be further expanded if necessary. 7931 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7932 case MVT::i32: 7933 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7934 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7935 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7936 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7937 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7938 DAG.getConstant(0xFF0000, dl, VT)); 7939 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7940 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7941 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7942 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7943 case MVT::i64: 7944 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7945 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7946 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7947 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7948 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7949 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7950 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7951 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7952 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7953 DAG.getConstant(255ULL<<48, dl, VT)); 7954 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7955 DAG.getConstant(255ULL<<40, dl, VT)); 7956 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7957 DAG.getConstant(255ULL<<32, dl, VT)); 7958 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7959 DAG.getConstant(255ULL<<24, dl, VT)); 7960 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7961 DAG.getConstant(255ULL<<16, dl, VT)); 7962 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7963 DAG.getConstant(255ULL<<8 , dl, VT)); 7964 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7965 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7966 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7967 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7968 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7969 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7970 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7971 } 7972 } 7973 7974 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 7975 SDLoc dl(N); 7976 EVT VT = N->getValueType(0); 7977 SDValue Op = N->getOperand(0); 7978 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7979 unsigned Sz = VT.getScalarSizeInBits(); 7980 7981 SDValue Tmp, Tmp2, Tmp3; 7982 7983 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 7984 // and finally the i1 pairs. 7985 // TODO: We can easily support i4/i2 legal types if any target ever does. 7986 if (Sz >= 8 && isPowerOf2_32(Sz)) { 7987 // Create the masks - repeating the pattern every byte. 7988 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 7989 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 7990 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 7991 7992 // BSWAP if the type is wider than a single byte. 7993 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 7994 7995 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 7996 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 7997 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 7998 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 7999 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8000 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8001 8002 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8003 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8004 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8005 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8006 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8007 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8008 8009 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8010 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8011 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8012 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8013 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8014 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8015 return Tmp; 8016 } 8017 8018 Tmp = DAG.getConstant(0, dl, VT); 8019 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8020 if (I < J) 8021 Tmp2 = 8022 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8023 else 8024 Tmp2 = 8025 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8026 8027 APInt Shift(Sz, 1); 8028 Shift <<= J; 8029 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8030 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8031 } 8032 8033 return Tmp; 8034 } 8035 8036 std::pair<SDValue, SDValue> 8037 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8038 SelectionDAG &DAG) const { 8039 SDLoc SL(LD); 8040 SDValue Chain = LD->getChain(); 8041 SDValue BasePTR = LD->getBasePtr(); 8042 EVT SrcVT = LD->getMemoryVT(); 8043 EVT DstVT = LD->getValueType(0); 8044 ISD::LoadExtType ExtType = LD->getExtensionType(); 8045 8046 if (SrcVT.isScalableVector()) 8047 report_fatal_error("Cannot scalarize scalable vector loads"); 8048 8049 unsigned NumElem = SrcVT.getVectorNumElements(); 8050 8051 EVT SrcEltVT = SrcVT.getScalarType(); 8052 EVT DstEltVT = DstVT.getScalarType(); 8053 8054 // A vector must always be stored in memory as-is, i.e. without any padding 8055 // between the elements, since various code depend on it, e.g. in the 8056 // handling of a bitcast of a vector type to int, which may be done with a 8057 // vector store followed by an integer load. A vector that does not have 8058 // elements that are byte-sized must therefore be stored as an integer 8059 // built out of the extracted vector elements. 8060 if (!SrcEltVT.isByteSized()) { 8061 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8062 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8063 8064 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8065 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8066 8067 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8068 SDValue SrcEltBitMask = DAG.getConstant( 8069 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8070 8071 // Load the whole vector and avoid masking off the top bits as it makes 8072 // the codegen worse. 8073 SDValue Load = 8074 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8075 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8076 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8077 8078 SmallVector<SDValue, 8> Vals; 8079 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8080 unsigned ShiftIntoIdx = 8081 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8082 SDValue ShiftAmount = 8083 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8084 LoadVT, SL, /*LegalTypes=*/false); 8085 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8086 SDValue Elt = 8087 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8088 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8089 8090 if (ExtType != ISD::NON_EXTLOAD) { 8091 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8092 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8093 } 8094 8095 Vals.push_back(Scalar); 8096 } 8097 8098 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8099 return std::make_pair(Value, Load.getValue(1)); 8100 } 8101 8102 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8103 assert(SrcEltVT.isByteSized()); 8104 8105 SmallVector<SDValue, 8> Vals; 8106 SmallVector<SDValue, 8> LoadChains; 8107 8108 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8109 SDValue ScalarLoad = 8110 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8111 LD->getPointerInfo().getWithOffset(Idx * Stride), 8112 SrcEltVT, LD->getOriginalAlign(), 8113 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8114 8115 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8116 8117 Vals.push_back(ScalarLoad.getValue(0)); 8118 LoadChains.push_back(ScalarLoad.getValue(1)); 8119 } 8120 8121 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8122 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8123 8124 return std::make_pair(Value, NewChain); 8125 } 8126 8127 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8128 SelectionDAG &DAG) const { 8129 SDLoc SL(ST); 8130 8131 SDValue Chain = ST->getChain(); 8132 SDValue BasePtr = ST->getBasePtr(); 8133 SDValue Value = ST->getValue(); 8134 EVT StVT = ST->getMemoryVT(); 8135 8136 if (StVT.isScalableVector()) 8137 report_fatal_error("Cannot scalarize scalable vector stores"); 8138 8139 // The type of the data we want to save 8140 EVT RegVT = Value.getValueType(); 8141 EVT RegSclVT = RegVT.getScalarType(); 8142 8143 // The type of data as saved in memory. 8144 EVT MemSclVT = StVT.getScalarType(); 8145 8146 unsigned NumElem = StVT.getVectorNumElements(); 8147 8148 // A vector must always be stored in memory as-is, i.e. without any padding 8149 // between the elements, since various code depend on it, e.g. in the 8150 // handling of a bitcast of a vector type to int, which may be done with a 8151 // vector store followed by an integer load. A vector that does not have 8152 // elements that are byte-sized must therefore be stored as an integer 8153 // built out of the extracted vector elements. 8154 if (!MemSclVT.isByteSized()) { 8155 unsigned NumBits = StVT.getSizeInBits(); 8156 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8157 8158 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8159 8160 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8161 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8162 DAG.getVectorIdxConstant(Idx, SL)); 8163 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8164 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8165 unsigned ShiftIntoIdx = 8166 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8167 SDValue ShiftAmount = 8168 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8169 SDValue ShiftedElt = 8170 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8171 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8172 } 8173 8174 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8175 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8176 ST->getAAInfo()); 8177 } 8178 8179 // Store Stride in bytes 8180 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8181 assert(Stride && "Zero stride!"); 8182 // Extract each of the elements from the original vector and save them into 8183 // memory individually. 8184 SmallVector<SDValue, 8> Stores; 8185 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8186 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8187 DAG.getVectorIdxConstant(Idx, SL)); 8188 8189 SDValue Ptr = 8190 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8191 8192 // This scalar TruncStore may be illegal, but we legalize it later. 8193 SDValue Store = DAG.getTruncStore( 8194 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8195 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8196 ST->getAAInfo()); 8197 8198 Stores.push_back(Store); 8199 } 8200 8201 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8202 } 8203 8204 std::pair<SDValue, SDValue> 8205 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8206 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8207 "unaligned indexed loads not implemented!"); 8208 SDValue Chain = LD->getChain(); 8209 SDValue Ptr = LD->getBasePtr(); 8210 EVT VT = LD->getValueType(0); 8211 EVT LoadedVT = LD->getMemoryVT(); 8212 SDLoc dl(LD); 8213 auto &MF = DAG.getMachineFunction(); 8214 8215 if (VT.isFloatingPoint() || VT.isVector()) { 8216 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8217 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8218 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8219 LoadedVT.isVector()) { 8220 // Scalarize the load and let the individual components be handled. 8221 return scalarizeVectorLoad(LD, DAG); 8222 } 8223 8224 // Expand to a (misaligned) integer load of the same size, 8225 // then bitconvert to floating point or vector. 8226 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8227 LD->getMemOperand()); 8228 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8229 if (LoadedVT != VT) 8230 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8231 ISD::ANY_EXTEND, dl, VT, Result); 8232 8233 return std::make_pair(Result, newLoad.getValue(1)); 8234 } 8235 8236 // Copy the value to a (aligned) stack slot using (unaligned) integer 8237 // loads and stores, then do a (aligned) load from the stack slot. 8238 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8239 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8240 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8241 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8242 8243 // Make sure the stack slot is also aligned for the register type. 8244 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8245 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8246 SmallVector<SDValue, 8> Stores; 8247 SDValue StackPtr = StackBase; 8248 unsigned Offset = 0; 8249 8250 EVT PtrVT = Ptr.getValueType(); 8251 EVT StackPtrVT = StackPtr.getValueType(); 8252 8253 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8254 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8255 8256 // Do all but one copies using the full register width. 8257 for (unsigned i = 1; i < NumRegs; i++) { 8258 // Load one integer register's worth from the original location. 8259 SDValue Load = DAG.getLoad( 8260 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8261 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8262 LD->getAAInfo()); 8263 // Follow the load with a store to the stack slot. Remember the store. 8264 Stores.push_back(DAG.getStore( 8265 Load.getValue(1), dl, Load, StackPtr, 8266 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8267 // Increment the pointers. 8268 Offset += RegBytes; 8269 8270 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8271 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8272 } 8273 8274 // The last copy may be partial. Do an extending load. 8275 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8276 8 * (LoadedBytes - Offset)); 8277 SDValue Load = 8278 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8279 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8280 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8281 LD->getAAInfo()); 8282 // Follow the load with a store to the stack slot. Remember the store. 8283 // On big-endian machines this requires a truncating store to ensure 8284 // that the bits end up in the right place. 8285 Stores.push_back(DAG.getTruncStore( 8286 Load.getValue(1), dl, Load, StackPtr, 8287 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8288 8289 // The order of the stores doesn't matter - say it with a TokenFactor. 8290 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8291 8292 // Finally, perform the original load only redirected to the stack slot. 8293 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8294 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8295 LoadedVT); 8296 8297 // Callers expect a MERGE_VALUES node. 8298 return std::make_pair(Load, TF); 8299 } 8300 8301 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8302 "Unaligned load of unsupported type."); 8303 8304 // Compute the new VT that is half the size of the old one. This is an 8305 // integer MVT. 8306 unsigned NumBits = LoadedVT.getSizeInBits(); 8307 EVT NewLoadedVT; 8308 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8309 NumBits >>= 1; 8310 8311 Align Alignment = LD->getOriginalAlign(); 8312 unsigned IncrementSize = NumBits / 8; 8313 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8314 8315 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8316 if (HiExtType == ISD::NON_EXTLOAD) 8317 HiExtType = ISD::ZEXTLOAD; 8318 8319 // Load the value in two parts 8320 SDValue Lo, Hi; 8321 if (DAG.getDataLayout().isLittleEndian()) { 8322 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8323 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8324 LD->getAAInfo()); 8325 8326 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8327 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8328 LD->getPointerInfo().getWithOffset(IncrementSize), 8329 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8330 LD->getAAInfo()); 8331 } else { 8332 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8333 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8334 LD->getAAInfo()); 8335 8336 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8337 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8338 LD->getPointerInfo().getWithOffset(IncrementSize), 8339 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8340 LD->getAAInfo()); 8341 } 8342 8343 // aggregate the two parts 8344 SDValue ShiftAmount = 8345 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8346 DAG.getDataLayout())); 8347 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8348 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8349 8350 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8351 Hi.getValue(1)); 8352 8353 return std::make_pair(Result, TF); 8354 } 8355 8356 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8357 SelectionDAG &DAG) const { 8358 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8359 "unaligned indexed stores not implemented!"); 8360 SDValue Chain = ST->getChain(); 8361 SDValue Ptr = ST->getBasePtr(); 8362 SDValue Val = ST->getValue(); 8363 EVT VT = Val.getValueType(); 8364 Align Alignment = ST->getOriginalAlign(); 8365 auto &MF = DAG.getMachineFunction(); 8366 EVT StoreMemVT = ST->getMemoryVT(); 8367 8368 SDLoc dl(ST); 8369 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8370 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8371 if (isTypeLegal(intVT)) { 8372 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8373 StoreMemVT.isVector()) { 8374 // Scalarize the store and let the individual components be handled. 8375 SDValue Result = scalarizeVectorStore(ST, DAG); 8376 return Result; 8377 } 8378 // Expand to a bitconvert of the value to the integer type of the 8379 // same size, then a (misaligned) int store. 8380 // FIXME: Does not handle truncating floating point stores! 8381 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8382 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8383 Alignment, ST->getMemOperand()->getFlags()); 8384 return Result; 8385 } 8386 // Do a (aligned) store to a stack slot, then copy from the stack slot 8387 // to the final destination using (unaligned) integer loads and stores. 8388 MVT RegVT = getRegisterType( 8389 *DAG.getContext(), 8390 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8391 EVT PtrVT = Ptr.getValueType(); 8392 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8393 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8394 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8395 8396 // Make sure the stack slot is also aligned for the register type. 8397 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8398 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8399 8400 // Perform the original store, only redirected to the stack slot. 8401 SDValue Store = DAG.getTruncStore( 8402 Chain, dl, Val, StackPtr, 8403 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8404 8405 EVT StackPtrVT = StackPtr.getValueType(); 8406 8407 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8408 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8409 SmallVector<SDValue, 8> Stores; 8410 unsigned Offset = 0; 8411 8412 // Do all but one copies using the full register width. 8413 for (unsigned i = 1; i < NumRegs; i++) { 8414 // Load one integer register's worth from the stack slot. 8415 SDValue Load = DAG.getLoad( 8416 RegVT, dl, Store, StackPtr, 8417 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8418 // Store it to the final location. Remember the store. 8419 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8420 ST->getPointerInfo().getWithOffset(Offset), 8421 ST->getOriginalAlign(), 8422 ST->getMemOperand()->getFlags())); 8423 // Increment the pointers. 8424 Offset += RegBytes; 8425 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8426 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8427 } 8428 8429 // The last store may be partial. Do a truncating store. On big-endian 8430 // machines this requires an extending load from the stack slot to ensure 8431 // that the bits are in the right place. 8432 EVT LoadMemVT = 8433 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8434 8435 // Load from the stack slot. 8436 SDValue Load = DAG.getExtLoad( 8437 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8438 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8439 8440 Stores.push_back( 8441 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8442 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8443 ST->getOriginalAlign(), 8444 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8445 // The order of the stores doesn't matter - say it with a TokenFactor. 8446 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8447 return Result; 8448 } 8449 8450 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8451 "Unaligned store of unknown type."); 8452 // Get the half-size VT 8453 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8454 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8455 unsigned IncrementSize = NumBits / 8; 8456 8457 // Divide the stored value in two parts. 8458 SDValue ShiftAmount = DAG.getConstant( 8459 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8460 SDValue Lo = Val; 8461 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8462 8463 // Store the two parts 8464 SDValue Store1, Store2; 8465 Store1 = DAG.getTruncStore(Chain, dl, 8466 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8467 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8468 ST->getMemOperand()->getFlags()); 8469 8470 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8471 Store2 = DAG.getTruncStore( 8472 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8473 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8474 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8475 8476 SDValue Result = 8477 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8478 return Result; 8479 } 8480 8481 SDValue 8482 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8483 const SDLoc &DL, EVT DataVT, 8484 SelectionDAG &DAG, 8485 bool IsCompressedMemory) const { 8486 SDValue Increment; 8487 EVT AddrVT = Addr.getValueType(); 8488 EVT MaskVT = Mask.getValueType(); 8489 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8490 "Incompatible types of Data and Mask"); 8491 if (IsCompressedMemory) { 8492 if (DataVT.isScalableVector()) 8493 report_fatal_error( 8494 "Cannot currently handle compressed memory with scalable vectors"); 8495 // Incrementing the pointer according to number of '1's in the mask. 8496 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8497 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8498 if (MaskIntVT.getSizeInBits() < 32) { 8499 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8500 MaskIntVT = MVT::i32; 8501 } 8502 8503 // Count '1's with POPCNT. 8504 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8505 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8506 // Scale is an element size in bytes. 8507 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8508 AddrVT); 8509 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8510 } else if (DataVT.isScalableVector()) { 8511 Increment = DAG.getVScale(DL, AddrVT, 8512 APInt(AddrVT.getFixedSizeInBits(), 8513 DataVT.getStoreSize().getKnownMinSize())); 8514 } else 8515 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8516 8517 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8518 } 8519 8520 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8521 EVT VecVT, const SDLoc &dl, 8522 ElementCount SubEC) { 8523 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8524 "Cannot index a scalable vector within a fixed-width vector"); 8525 8526 unsigned NElts = VecVT.getVectorMinNumElements(); 8527 unsigned NumSubElts = SubEC.getKnownMinValue(); 8528 EVT IdxVT = Idx.getValueType(); 8529 8530 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8531 // If this is a constant index and we know the value plus the number of the 8532 // elements in the subvector minus one is less than the minimum number of 8533 // elements then it's safe to return Idx. 8534 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8535 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8536 return Idx; 8537 SDValue VS = 8538 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8539 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8540 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8541 DAG.getConstant(NumSubElts, dl, IdxVT)); 8542 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8543 } 8544 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8545 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8546 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8547 DAG.getConstant(Imm, dl, IdxVT)); 8548 } 8549 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8550 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8551 DAG.getConstant(MaxIndex, dl, IdxVT)); 8552 } 8553 8554 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8555 SDValue VecPtr, EVT VecVT, 8556 SDValue Index) const { 8557 return getVectorSubVecPointer( 8558 DAG, VecPtr, VecVT, 8559 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8560 Index); 8561 } 8562 8563 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8564 SDValue VecPtr, EVT VecVT, 8565 EVT SubVecVT, 8566 SDValue Index) const { 8567 SDLoc dl(Index); 8568 // Make sure the index type is big enough to compute in. 8569 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8570 8571 EVT EltVT = VecVT.getVectorElementType(); 8572 8573 // Calculate the element offset and add it to the pointer. 8574 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8575 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8576 "Converting bits to bytes lost precision"); 8577 assert(SubVecVT.getVectorElementType() == EltVT && 8578 "Sub-vector must be a vector with matching element type"); 8579 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8580 SubVecVT.getVectorElementCount()); 8581 8582 EVT IdxVT = Index.getValueType(); 8583 if (SubVecVT.isScalableVector()) 8584 Index = 8585 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8586 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8587 8588 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8589 DAG.getConstant(EltSize, dl, IdxVT)); 8590 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8591 } 8592 8593 //===----------------------------------------------------------------------===// 8594 // Implementation of Emulated TLS Model 8595 //===----------------------------------------------------------------------===// 8596 8597 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8598 SelectionDAG &DAG) const { 8599 // Access to address of TLS varialbe xyz is lowered to a function call: 8600 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8601 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8602 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8603 SDLoc dl(GA); 8604 8605 ArgListTy Args; 8606 ArgListEntry Entry; 8607 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8608 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8609 StringRef EmuTlsVarName(NameString); 8610 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8611 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8612 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8613 Entry.Ty = VoidPtrType; 8614 Args.push_back(Entry); 8615 8616 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8617 8618 TargetLowering::CallLoweringInfo CLI(DAG); 8619 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8620 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8621 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8622 8623 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8624 // At last for X86 targets, maybe good for other targets too? 8625 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8626 MFI.setAdjustsStack(true); // Is this only for X86 target? 8627 MFI.setHasCalls(true); 8628 8629 assert((GA->getOffset() == 0) && 8630 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8631 return CallResult.first; 8632 } 8633 8634 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8635 SelectionDAG &DAG) const { 8636 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8637 if (!isCtlzFast()) 8638 return SDValue(); 8639 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8640 SDLoc dl(Op); 8641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8642 if (C->isZero() && CC == ISD::SETEQ) { 8643 EVT VT = Op.getOperand(0).getValueType(); 8644 SDValue Zext = Op.getOperand(0); 8645 if (VT.bitsLT(MVT::i32)) { 8646 VT = MVT::i32; 8647 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8648 } 8649 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8650 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8651 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8652 DAG.getConstant(Log2b, dl, MVT::i32)); 8653 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8654 } 8655 } 8656 return SDValue(); 8657 } 8658 8659 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8660 SDValue Op0 = Node->getOperand(0); 8661 SDValue Op1 = Node->getOperand(1); 8662 EVT VT = Op0.getValueType(); 8663 unsigned Opcode = Node->getOpcode(); 8664 SDLoc DL(Node); 8665 8666 // umin(x,y) -> sub(x,usubsat(x,y)) 8667 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8668 isOperationLegal(ISD::USUBSAT, VT)) { 8669 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8670 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8671 } 8672 8673 // umax(x,y) -> add(x,usubsat(y,x)) 8674 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8675 isOperationLegal(ISD::USUBSAT, VT)) { 8676 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8677 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8678 } 8679 8680 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8681 ISD::CondCode CC; 8682 switch (Opcode) { 8683 default: llvm_unreachable("How did we get here?"); 8684 case ISD::SMAX: CC = ISD::SETGT; break; 8685 case ISD::SMIN: CC = ISD::SETLT; break; 8686 case ISD::UMAX: CC = ISD::SETUGT; break; 8687 case ISD::UMIN: CC = ISD::SETULT; break; 8688 } 8689 8690 // FIXME: Should really try to split the vector in case it's legal on a 8691 // subvector. 8692 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8693 return DAG.UnrollVectorOp(Node); 8694 8695 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8696 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8697 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8698 } 8699 8700 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8701 unsigned Opcode = Node->getOpcode(); 8702 SDValue LHS = Node->getOperand(0); 8703 SDValue RHS = Node->getOperand(1); 8704 EVT VT = LHS.getValueType(); 8705 SDLoc dl(Node); 8706 8707 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8708 assert(VT.isInteger() && "Expected operands to be integers"); 8709 8710 // usub.sat(a, b) -> umax(a, b) - b 8711 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8712 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8713 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8714 } 8715 8716 // uadd.sat(a, b) -> umin(a, ~b) + b 8717 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8718 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8719 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8720 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8721 } 8722 8723 unsigned OverflowOp; 8724 switch (Opcode) { 8725 case ISD::SADDSAT: 8726 OverflowOp = ISD::SADDO; 8727 break; 8728 case ISD::UADDSAT: 8729 OverflowOp = ISD::UADDO; 8730 break; 8731 case ISD::SSUBSAT: 8732 OverflowOp = ISD::SSUBO; 8733 break; 8734 case ISD::USUBSAT: 8735 OverflowOp = ISD::USUBO; 8736 break; 8737 default: 8738 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8739 "addition or subtraction node."); 8740 } 8741 8742 // FIXME: Should really try to split the vector in case it's legal on a 8743 // subvector. 8744 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8745 return DAG.UnrollVectorOp(Node); 8746 8747 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8748 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8749 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8750 SDValue SumDiff = Result.getValue(0); 8751 SDValue Overflow = Result.getValue(1); 8752 SDValue Zero = DAG.getConstant(0, dl, VT); 8753 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8754 8755 if (Opcode == ISD::UADDSAT) { 8756 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8757 // (LHS + RHS) | OverflowMask 8758 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8759 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8760 } 8761 // Overflow ? 0xffff.... : (LHS + RHS) 8762 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8763 } 8764 8765 if (Opcode == ISD::USUBSAT) { 8766 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8767 // (LHS - RHS) & ~OverflowMask 8768 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8769 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8770 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8771 } 8772 // Overflow ? 0 : (LHS - RHS) 8773 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8774 } 8775 8776 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8777 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8778 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8779 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8780 DAG.getConstant(BitWidth - 1, dl, VT)); 8781 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8782 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8783 } 8784 8785 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8786 unsigned Opcode = Node->getOpcode(); 8787 bool IsSigned = Opcode == ISD::SSHLSAT; 8788 SDValue LHS = Node->getOperand(0); 8789 SDValue RHS = Node->getOperand(1); 8790 EVT VT = LHS.getValueType(); 8791 SDLoc dl(Node); 8792 8793 assert((Node->getOpcode() == ISD::SSHLSAT || 8794 Node->getOpcode() == ISD::USHLSAT) && 8795 "Expected a SHLSAT opcode"); 8796 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8797 assert(VT.isInteger() && "Expected operands to be integers"); 8798 8799 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8800 8801 unsigned BW = VT.getScalarSizeInBits(); 8802 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8803 SDValue Orig = 8804 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8805 8806 SDValue SatVal; 8807 if (IsSigned) { 8808 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8809 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8810 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8811 SatMin, SatMax, ISD::SETLT); 8812 } else { 8813 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8814 } 8815 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8816 8817 return Result; 8818 } 8819 8820 SDValue 8821 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8822 assert((Node->getOpcode() == ISD::SMULFIX || 8823 Node->getOpcode() == ISD::UMULFIX || 8824 Node->getOpcode() == ISD::SMULFIXSAT || 8825 Node->getOpcode() == ISD::UMULFIXSAT) && 8826 "Expected a fixed point multiplication opcode"); 8827 8828 SDLoc dl(Node); 8829 SDValue LHS = Node->getOperand(0); 8830 SDValue RHS = Node->getOperand(1); 8831 EVT VT = LHS.getValueType(); 8832 unsigned Scale = Node->getConstantOperandVal(2); 8833 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8834 Node->getOpcode() == ISD::UMULFIXSAT); 8835 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8836 Node->getOpcode() == ISD::SMULFIXSAT); 8837 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8838 unsigned VTSize = VT.getScalarSizeInBits(); 8839 8840 if (!Scale) { 8841 // [us]mul.fix(a, b, 0) -> mul(a, b) 8842 if (!Saturating) { 8843 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8844 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8845 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8846 SDValue Result = 8847 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8848 SDValue Product = Result.getValue(0); 8849 SDValue Overflow = Result.getValue(1); 8850 SDValue Zero = DAG.getConstant(0, dl, VT); 8851 8852 APInt MinVal = APInt::getSignedMinValue(VTSize); 8853 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8854 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8855 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8856 // Xor the inputs, if resulting sign bit is 0 the product will be 8857 // positive, else negative. 8858 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8859 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8860 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8861 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8862 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8863 SDValue Result = 8864 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8865 SDValue Product = Result.getValue(0); 8866 SDValue Overflow = Result.getValue(1); 8867 8868 APInt MaxVal = APInt::getMaxValue(VTSize); 8869 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8870 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8871 } 8872 } 8873 8874 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8875 "Expected scale to be less than the number of bits if signed or at " 8876 "most the number of bits if unsigned."); 8877 assert(LHS.getValueType() == RHS.getValueType() && 8878 "Expected both operands to be the same type"); 8879 8880 // Get the upper and lower bits of the result. 8881 SDValue Lo, Hi; 8882 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8883 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8884 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8885 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8886 Lo = Result.getValue(0); 8887 Hi = Result.getValue(1); 8888 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8889 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8890 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8891 } else if (VT.isVector()) { 8892 return SDValue(); 8893 } else { 8894 report_fatal_error("Unable to expand fixed point multiplication."); 8895 } 8896 8897 if (Scale == VTSize) 8898 // Result is just the top half since we'd be shifting by the width of the 8899 // operand. Overflow impossible so this works for both UMULFIX and 8900 // UMULFIXSAT. 8901 return Hi; 8902 8903 // The result will need to be shifted right by the scale since both operands 8904 // are scaled. The result is given to us in 2 halves, so we only want part of 8905 // both in the result. 8906 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8907 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8908 DAG.getConstant(Scale, dl, ShiftTy)); 8909 if (!Saturating) 8910 return Result; 8911 8912 if (!Signed) { 8913 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8914 // widened multiplication) aren't all zeroes. 8915 8916 // Saturate to max if ((Hi >> Scale) != 0), 8917 // which is the same as if (Hi > ((1 << Scale) - 1)) 8918 APInt MaxVal = APInt::getMaxValue(VTSize); 8919 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8920 dl, VT); 8921 Result = DAG.getSelectCC(dl, Hi, LowMask, 8922 DAG.getConstant(MaxVal, dl, VT), Result, 8923 ISD::SETUGT); 8924 8925 return Result; 8926 } 8927 8928 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8929 // widened multiplication) aren't all ones or all zeroes. 8930 8931 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8932 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8933 8934 if (Scale == 0) { 8935 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8936 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8937 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8938 // Saturated to SatMin if wide product is negative, and SatMax if wide 8939 // product is positive ... 8940 SDValue Zero = DAG.getConstant(0, dl, VT); 8941 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8942 ISD::SETLT); 8943 // ... but only if we overflowed. 8944 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 8945 } 8946 8947 // We handled Scale==0 above so all the bits to examine is in Hi. 8948 8949 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 8950 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 8951 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 8952 dl, VT); 8953 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 8954 // Saturate to min if (Hi >> (Scale - 1)) < -1), 8955 // which is the same as if (HI < (-1 << (Scale - 1)) 8956 SDValue HighMask = 8957 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 8958 dl, VT); 8959 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 8960 return Result; 8961 } 8962 8963 SDValue 8964 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 8965 SDValue LHS, SDValue RHS, 8966 unsigned Scale, SelectionDAG &DAG) const { 8967 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 8968 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 8969 "Expected a fixed point division opcode"); 8970 8971 EVT VT = LHS.getValueType(); 8972 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 8973 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 8974 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8975 8976 // If there is enough room in the type to upscale the LHS or downscale the 8977 // RHS before the division, we can perform it in this type without having to 8978 // resize. For signed operations, the LHS headroom is the number of 8979 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8980 // The headroom for the RHS is the number of trailing zeroes. 8981 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8982 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8983 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 8984 8985 // For signed saturating operations, we need to be able to detect true integer 8986 // division overflow; that is, when you have MIN / -EPS. However, this 8987 // is undefined behavior and if we emit divisions that could take such 8988 // values it may cause undesired behavior (arithmetic exceptions on x86, for 8989 // example). 8990 // Avoid this by requiring an extra bit so that we never get this case. 8991 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 8992 // signed saturating division, we need to emit a whopping 32-bit division. 8993 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 8994 return SDValue(); 8995 8996 unsigned LHSShift = std::min(LHSLead, Scale); 8997 unsigned RHSShift = Scale - LHSShift; 8998 8999 // At this point, we know that if we shift the LHS up by LHSShift and the 9000 // RHS down by RHSShift, we can emit a regular division with a final scaling 9001 // factor of Scale. 9002 9003 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9004 if (LHSShift) 9005 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9006 DAG.getConstant(LHSShift, dl, ShiftTy)); 9007 if (RHSShift) 9008 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9009 DAG.getConstant(RHSShift, dl, ShiftTy)); 9010 9011 SDValue Quot; 9012 if (Signed) { 9013 // For signed operations, if the resulting quotient is negative and the 9014 // remainder is nonzero, subtract 1 from the quotient to round towards 9015 // negative infinity. 9016 SDValue Rem; 9017 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9018 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9019 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9020 if (isTypeLegal(VT) && 9021 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9022 Quot = DAG.getNode(ISD::SDIVREM, dl, 9023 DAG.getVTList(VT, VT), 9024 LHS, RHS); 9025 Rem = Quot.getValue(1); 9026 Quot = Quot.getValue(0); 9027 } else { 9028 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9029 LHS, RHS); 9030 Rem = DAG.getNode(ISD::SREM, dl, VT, 9031 LHS, RHS); 9032 } 9033 SDValue Zero = DAG.getConstant(0, dl, VT); 9034 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9035 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9036 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9037 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9038 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9039 DAG.getConstant(1, dl, VT)); 9040 Quot = DAG.getSelect(dl, VT, 9041 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9042 Sub1, Quot); 9043 } else 9044 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9045 LHS, RHS); 9046 9047 return Quot; 9048 } 9049 9050 void TargetLowering::expandUADDSUBO( 9051 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9052 SDLoc dl(Node); 9053 SDValue LHS = Node->getOperand(0); 9054 SDValue RHS = Node->getOperand(1); 9055 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9056 9057 // If ADD/SUBCARRY is legal, use that instead. 9058 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9059 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9060 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9061 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9062 { LHS, RHS, CarryIn }); 9063 Result = SDValue(NodeCarry.getNode(), 0); 9064 Overflow = SDValue(NodeCarry.getNode(), 1); 9065 return; 9066 } 9067 9068 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9069 LHS.getValueType(), LHS, RHS); 9070 9071 EVT ResultType = Node->getValueType(1); 9072 EVT SetCCType = getSetCCResultType( 9073 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9074 SDValue SetCC; 9075 if (IsAdd && isOneConstant(RHS)) { 9076 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9077 // the live range of X. We assume comparing with 0 is cheap. 9078 // The general case (X + C) < C is not necessarily beneficial. Although we 9079 // reduce the live range of X, we may introduce the materialization of 9080 // constant C. 9081 SetCC = 9082 DAG.getSetCC(dl, SetCCType, Result, 9083 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9084 } else { 9085 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9086 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9087 } 9088 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9089 } 9090 9091 void TargetLowering::expandSADDSUBO( 9092 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9093 SDLoc dl(Node); 9094 SDValue LHS = Node->getOperand(0); 9095 SDValue RHS = Node->getOperand(1); 9096 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9097 9098 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9099 LHS.getValueType(), LHS, RHS); 9100 9101 EVT ResultType = Node->getValueType(1); 9102 EVT OType = getSetCCResultType( 9103 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9104 9105 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9106 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9107 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9108 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9109 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9110 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9111 return; 9112 } 9113 9114 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9115 9116 // For an addition, the result should be less than one of the operands (LHS) 9117 // if and only if the other operand (RHS) is negative, otherwise there will 9118 // be overflow. 9119 // For a subtraction, the result should be less than one of the operands 9120 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9121 // otherwise there will be overflow. 9122 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9123 SDValue ConditionRHS = 9124 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9125 9126 Overflow = DAG.getBoolExtOrTrunc( 9127 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9128 ResultType, ResultType); 9129 } 9130 9131 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9132 SDValue &Overflow, SelectionDAG &DAG) const { 9133 SDLoc dl(Node); 9134 EVT VT = Node->getValueType(0); 9135 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9136 SDValue LHS = Node->getOperand(0); 9137 SDValue RHS = Node->getOperand(1); 9138 bool isSigned = Node->getOpcode() == ISD::SMULO; 9139 9140 // For power-of-two multiplications we can use a simpler shift expansion. 9141 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9142 const APInt &C = RHSC->getAPIntValue(); 9143 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9144 if (C.isPowerOf2()) { 9145 // smulo(x, signed_min) is same as umulo(x, signed_min). 9146 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9147 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9148 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9149 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9150 Overflow = DAG.getSetCC(dl, SetCCVT, 9151 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9152 dl, VT, Result, ShiftAmt), 9153 LHS, ISD::SETNE); 9154 return true; 9155 } 9156 } 9157 9158 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9159 if (VT.isVector()) 9160 WideVT = 9161 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9162 9163 SDValue BottomHalf; 9164 SDValue TopHalf; 9165 static const unsigned Ops[2][3] = 9166 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9167 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9168 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9169 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9170 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9171 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9172 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9173 RHS); 9174 TopHalf = BottomHalf.getValue(1); 9175 } else if (isTypeLegal(WideVT)) { 9176 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9177 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9178 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9179 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9180 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9181 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9182 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9183 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9184 } else { 9185 if (VT.isVector()) 9186 return false; 9187 9188 // We can fall back to a libcall with an illegal type for the MUL if we 9189 // have a libcall big enough. 9190 // Also, we can fall back to a division in some cases, but that's a big 9191 // performance hit in the general case. 9192 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9193 if (WideVT == MVT::i16) 9194 LC = RTLIB::MUL_I16; 9195 else if (WideVT == MVT::i32) 9196 LC = RTLIB::MUL_I32; 9197 else if (WideVT == MVT::i64) 9198 LC = RTLIB::MUL_I64; 9199 else if (WideVT == MVT::i128) 9200 LC = RTLIB::MUL_I128; 9201 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9202 9203 SDValue HiLHS; 9204 SDValue HiRHS; 9205 if (isSigned) { 9206 // The high part is obtained by SRA'ing all but one of the bits of low 9207 // part. 9208 unsigned LoSize = VT.getFixedSizeInBits(); 9209 HiLHS = 9210 DAG.getNode(ISD::SRA, dl, VT, LHS, 9211 DAG.getConstant(LoSize - 1, dl, 9212 getPointerTy(DAG.getDataLayout()))); 9213 HiRHS = 9214 DAG.getNode(ISD::SRA, dl, VT, RHS, 9215 DAG.getConstant(LoSize - 1, dl, 9216 getPointerTy(DAG.getDataLayout()))); 9217 } else { 9218 HiLHS = DAG.getConstant(0, dl, VT); 9219 HiRHS = DAG.getConstant(0, dl, VT); 9220 } 9221 9222 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9223 // pre-lowered to the correct types. This all depends upon WideVT not 9224 // being a legal type for the architecture and thus has to be split to 9225 // two arguments. 9226 SDValue Ret; 9227 TargetLowering::MakeLibCallOptions CallOptions; 9228 CallOptions.setSExt(isSigned); 9229 CallOptions.setIsPostTypeLegalization(true); 9230 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9231 // Halves of WideVT are packed into registers in different order 9232 // depending on platform endianness. This is usually handled by 9233 // the C calling convention, but we can't defer to it in 9234 // the legalizer. 9235 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9236 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9237 } else { 9238 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9239 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9240 } 9241 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9242 "Ret value is a collection of constituent nodes holding result."); 9243 if (DAG.getDataLayout().isLittleEndian()) { 9244 // Same as above. 9245 BottomHalf = Ret.getOperand(0); 9246 TopHalf = Ret.getOperand(1); 9247 } else { 9248 BottomHalf = Ret.getOperand(1); 9249 TopHalf = Ret.getOperand(0); 9250 } 9251 } 9252 9253 Result = BottomHalf; 9254 if (isSigned) { 9255 SDValue ShiftAmt = DAG.getConstant( 9256 VT.getScalarSizeInBits() - 1, dl, 9257 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9258 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9259 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9260 } else { 9261 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9262 DAG.getConstant(0, dl, VT), ISD::SETNE); 9263 } 9264 9265 // Truncate the result if SetCC returns a larger type than needed. 9266 EVT RType = Node->getValueType(1); 9267 if (RType.bitsLT(Overflow.getValueType())) 9268 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9269 9270 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9271 "Unexpected result type for S/UMULO legalization"); 9272 return true; 9273 } 9274 9275 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9276 SDLoc dl(Node); 9277 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9278 SDValue Op = Node->getOperand(0); 9279 EVT VT = Op.getValueType(); 9280 9281 if (VT.isScalableVector()) 9282 report_fatal_error( 9283 "Expanding reductions for scalable vectors is undefined."); 9284 9285 // Try to use a shuffle reduction for power of two vectors. 9286 if (VT.isPow2VectorType()) { 9287 while (VT.getVectorNumElements() > 1) { 9288 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9289 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9290 break; 9291 9292 SDValue Lo, Hi; 9293 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9294 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9295 VT = HalfVT; 9296 } 9297 } 9298 9299 EVT EltVT = VT.getVectorElementType(); 9300 unsigned NumElts = VT.getVectorNumElements(); 9301 9302 SmallVector<SDValue, 8> Ops; 9303 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9304 9305 SDValue Res = Ops[0]; 9306 for (unsigned i = 1; i < NumElts; i++) 9307 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9308 9309 // Result type may be wider than element type. 9310 if (EltVT != Node->getValueType(0)) 9311 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9312 return Res; 9313 } 9314 9315 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9316 SDLoc dl(Node); 9317 SDValue AccOp = Node->getOperand(0); 9318 SDValue VecOp = Node->getOperand(1); 9319 SDNodeFlags Flags = Node->getFlags(); 9320 9321 EVT VT = VecOp.getValueType(); 9322 EVT EltVT = VT.getVectorElementType(); 9323 9324 if (VT.isScalableVector()) 9325 report_fatal_error( 9326 "Expanding reductions for scalable vectors is undefined."); 9327 9328 unsigned NumElts = VT.getVectorNumElements(); 9329 9330 SmallVector<SDValue, 8> Ops; 9331 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9332 9333 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9334 9335 SDValue Res = AccOp; 9336 for (unsigned i = 0; i < NumElts; i++) 9337 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9338 9339 return Res; 9340 } 9341 9342 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9343 SelectionDAG &DAG) const { 9344 EVT VT = Node->getValueType(0); 9345 SDLoc dl(Node); 9346 bool isSigned = Node->getOpcode() == ISD::SREM; 9347 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9348 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9349 SDValue Dividend = Node->getOperand(0); 9350 SDValue Divisor = Node->getOperand(1); 9351 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9352 SDVTList VTs = DAG.getVTList(VT, VT); 9353 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9354 return true; 9355 } 9356 if (isOperationLegalOrCustom(DivOpc, VT)) { 9357 // X % Y -> X-X/Y*Y 9358 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9359 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9360 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9361 return true; 9362 } 9363 return false; 9364 } 9365 9366 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9367 SelectionDAG &DAG) const { 9368 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9369 SDLoc dl(SDValue(Node, 0)); 9370 SDValue Src = Node->getOperand(0); 9371 9372 // DstVT is the result type, while SatVT is the size to which we saturate 9373 EVT SrcVT = Src.getValueType(); 9374 EVT DstVT = Node->getValueType(0); 9375 9376 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9377 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9378 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9379 assert(SatWidth <= DstWidth && 9380 "Expected saturation width smaller than result width"); 9381 9382 // Determine minimum and maximum integer values and their corresponding 9383 // floating-point values. 9384 APInt MinInt, MaxInt; 9385 if (IsSigned) { 9386 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9387 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9388 } else { 9389 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9390 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9391 } 9392 9393 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9394 // libcall emission cannot handle this. Large result types will fail. 9395 if (SrcVT == MVT::f16) { 9396 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9397 SrcVT = Src.getValueType(); 9398 } 9399 9400 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9401 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9402 9403 APFloat::opStatus MinStatus = 9404 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9405 APFloat::opStatus MaxStatus = 9406 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9407 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9408 !(MaxStatus & APFloat::opStatus::opInexact); 9409 9410 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9411 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9412 9413 // If the integer bounds are exactly representable as floats and min/max are 9414 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9415 // of comparisons and selects. 9416 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9417 isOperationLegal(ISD::FMAXNUM, SrcVT); 9418 if (AreExactFloatBounds && MinMaxLegal) { 9419 SDValue Clamped = Src; 9420 9421 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9422 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9423 // Clamp by MaxFloat from above. NaN cannot occur. 9424 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9425 // Convert clamped value to integer. 9426 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9427 dl, DstVT, Clamped); 9428 9429 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9430 // which will cast to zero. 9431 if (!IsSigned) 9432 return FpToInt; 9433 9434 // Otherwise, select 0 if Src is NaN. 9435 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9436 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9437 ISD::CondCode::SETUO); 9438 } 9439 9440 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9441 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9442 9443 // Result of direct conversion. The assumption here is that the operation is 9444 // non-trapping and it's fine to apply it to an out-of-range value if we 9445 // select it away later. 9446 SDValue FpToInt = 9447 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9448 9449 SDValue Select = FpToInt; 9450 9451 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9452 // MinInt if Src is NaN. 9453 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9454 ISD::CondCode::SETULT); 9455 // If Src OGT MaxFloat, select MaxInt. 9456 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9457 ISD::CondCode::SETOGT); 9458 9459 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9460 // is already zero. 9461 if (!IsSigned) 9462 return Select; 9463 9464 // Otherwise, select 0 if Src is NaN. 9465 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9466 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9467 } 9468 9469 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9470 SelectionDAG &DAG) const { 9471 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9472 assert(Node->getValueType(0).isScalableVector() && 9473 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9474 9475 EVT VT = Node->getValueType(0); 9476 SDValue V1 = Node->getOperand(0); 9477 SDValue V2 = Node->getOperand(1); 9478 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9479 SDLoc DL(Node); 9480 9481 // Expand through memory thusly: 9482 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9483 // Store V1, Ptr 9484 // Store V2, Ptr + sizeof(V1) 9485 // If (Imm < 0) 9486 // TrailingElts = -Imm 9487 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9488 // else 9489 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9490 // Res = Load Ptr 9491 9492 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9493 9494 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9495 VT.getVectorElementCount() * 2); 9496 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9497 EVT PtrVT = StackPtr.getValueType(); 9498 auto &MF = DAG.getMachineFunction(); 9499 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9500 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9501 9502 // Store the lo part of CONCAT_VECTORS(V1, V2) 9503 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9504 // Store the hi part of CONCAT_VECTORS(V1, V2) 9505 SDValue OffsetToV2 = DAG.getVScale( 9506 DL, PtrVT, 9507 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9508 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9509 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9510 9511 if (Imm >= 0) { 9512 // Load back the required element. getVectorElementPointer takes care of 9513 // clamping the index if it's out-of-bounds. 9514 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9515 // Load the spliced result 9516 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9517 MachinePointerInfo::getUnknownStack(MF)); 9518 } 9519 9520 uint64_t TrailingElts = -Imm; 9521 9522 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9523 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9524 SDValue TrailingBytes = 9525 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9526 9527 if (TrailingElts > VT.getVectorMinNumElements()) { 9528 SDValue VLBytes = DAG.getVScale( 9529 DL, PtrVT, 9530 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9531 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9532 } 9533 9534 // Calculate the start address of the spliced result. 9535 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9536 9537 // Load the spliced result 9538 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9539 MachinePointerInfo::getUnknownStack(MF)); 9540 } 9541 9542 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9543 SDValue &LHS, SDValue &RHS, 9544 SDValue &CC, SDValue Mask, 9545 SDValue EVL, bool &NeedInvert, 9546 const SDLoc &dl, SDValue &Chain, 9547 bool IsSignaling) const { 9548 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9549 MVT OpVT = LHS.getSimpleValueType(); 9550 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9551 NeedInvert = false; 9552 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9553 bool IsNonVP = !EVL; 9554 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9555 default: 9556 llvm_unreachable("Unknown condition code action!"); 9557 case TargetLowering::Legal: 9558 // Nothing to do. 9559 break; 9560 case TargetLowering::Expand: { 9561 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9562 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9563 std::swap(LHS, RHS); 9564 CC = DAG.getCondCode(InvCC); 9565 return true; 9566 } 9567 // Swapping operands didn't work. Try inverting the condition. 9568 bool NeedSwap = false; 9569 InvCC = getSetCCInverse(CCCode, OpVT); 9570 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9571 // If inverting the condition is not enough, try swapping operands 9572 // on top of it. 9573 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9574 NeedSwap = true; 9575 } 9576 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9577 CC = DAG.getCondCode(InvCC); 9578 NeedInvert = true; 9579 if (NeedSwap) 9580 std::swap(LHS, RHS); 9581 return true; 9582 } 9583 9584 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9585 unsigned Opc = 0; 9586 switch (CCCode) { 9587 default: 9588 llvm_unreachable("Don't know how to expand this condition!"); 9589 case ISD::SETUO: 9590 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9591 CC1 = ISD::SETUNE; 9592 CC2 = ISD::SETUNE; 9593 Opc = ISD::OR; 9594 break; 9595 } 9596 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9597 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9598 NeedInvert = true; 9599 LLVM_FALLTHROUGH; 9600 case ISD::SETO: 9601 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9602 "If SETO is expanded, SETOEQ must be legal!"); 9603 CC1 = ISD::SETOEQ; 9604 CC2 = ISD::SETOEQ; 9605 Opc = ISD::AND; 9606 break; 9607 case ISD::SETONE: 9608 case ISD::SETUEQ: 9609 // If the SETUO or SETO CC isn't legal, we might be able to use 9610 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9611 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9612 // the operands. 9613 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9614 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9615 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9616 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9617 CC1 = ISD::SETOGT; 9618 CC2 = ISD::SETOLT; 9619 Opc = ISD::OR; 9620 NeedInvert = ((unsigned)CCCode & 0x8U); 9621 break; 9622 } 9623 LLVM_FALLTHROUGH; 9624 case ISD::SETOEQ: 9625 case ISD::SETOGT: 9626 case ISD::SETOGE: 9627 case ISD::SETOLT: 9628 case ISD::SETOLE: 9629 case ISD::SETUNE: 9630 case ISD::SETUGT: 9631 case ISD::SETUGE: 9632 case ISD::SETULT: 9633 case ISD::SETULE: 9634 // If we are floating point, assign and break, otherwise fall through. 9635 if (!OpVT.isInteger()) { 9636 // We can use the 4th bit to tell if we are the unordered 9637 // or ordered version of the opcode. 9638 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9639 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9640 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9641 break; 9642 } 9643 // Fallthrough if we are unsigned integer. 9644 LLVM_FALLTHROUGH; 9645 case ISD::SETLE: 9646 case ISD::SETGT: 9647 case ISD::SETGE: 9648 case ISD::SETLT: 9649 case ISD::SETNE: 9650 case ISD::SETEQ: 9651 // If all combinations of inverting the condition and swapping operands 9652 // didn't work then we have no means to expand the condition. 9653 llvm_unreachable("Don't know how to expand this condition!"); 9654 } 9655 9656 SDValue SetCC1, SetCC2; 9657 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9658 // If we aren't the ordered or unorder operation, 9659 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9660 if (IsNonVP) { 9661 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9662 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9663 } else { 9664 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9665 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9666 } 9667 } else { 9668 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9669 if (IsNonVP) { 9670 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9671 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9672 } else { 9673 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9674 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9675 } 9676 } 9677 if (Chain) 9678 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9679 SetCC2.getValue(1)); 9680 if (IsNonVP) 9681 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9682 else { 9683 // Transform the binary opcode to the VP equivalent. 9684 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9685 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9686 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9687 } 9688 RHS = SDValue(); 9689 CC = SDValue(); 9690 return true; 9691 } 9692 } 9693 return false; 9694 } 9695