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 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1366 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1367 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && 1368 (Op0.getOperand(0).isUndef() || 1369 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1370 Op0->hasOneUse()) { 1371 unsigned NumSubElts = 1372 Op0.getOperand(1).getValueType().getVectorNumElements(); 1373 unsigned SubIdx = Op0.getConstantOperandVal(2); 1374 APInt DemandedSub = 1375 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1376 KnownBits KnownSubMask = 1377 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1378 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1379 SDValue NewAnd = 1380 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1381 SDValue NewInsert = 1382 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1383 Op0.getOperand(1), Op0.getOperand(2)); 1384 return TLO.CombineTo(Op, NewInsert); 1385 } 1386 } 1387 1388 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1389 Depth + 1)) 1390 return true; 1391 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1392 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1393 Known2, TLO, Depth + 1)) 1394 return true; 1395 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1396 1397 // If all of the demanded bits are known one on one side, return the other. 1398 // These bits cannot contribute to the result of the 'and'. 1399 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1400 return TLO.CombineTo(Op, Op0); 1401 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1402 return TLO.CombineTo(Op, Op1); 1403 // If all of the demanded bits in the inputs are known zeros, return zero. 1404 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1405 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1406 // If the RHS is a constant, see if we can simplify it. 1407 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1408 TLO)) 1409 return true; 1410 // If the operation can be done in a smaller type, do so. 1411 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1412 return true; 1413 1414 // Attempt to avoid multi-use ops if we don't need anything from them. 1415 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1416 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1417 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1418 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1419 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1420 if (DemandedOp0 || DemandedOp1) { 1421 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1422 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1423 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1424 return TLO.CombineTo(Op, NewOp); 1425 } 1426 } 1427 1428 Known &= Known2; 1429 break; 1430 } 1431 case ISD::OR: { 1432 SDValue Op0 = Op.getOperand(0); 1433 SDValue Op1 = Op.getOperand(1); 1434 1435 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1436 Depth + 1)) 1437 return true; 1438 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1439 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1440 Known2, TLO, Depth + 1)) 1441 return true; 1442 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1443 1444 // If all of the demanded bits are known zero on one side, return the other. 1445 // These bits cannot contribute to the result of the 'or'. 1446 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1447 return TLO.CombineTo(Op, Op0); 1448 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1449 return TLO.CombineTo(Op, Op1); 1450 // If the RHS is a constant, see if we can simplify it. 1451 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1452 return true; 1453 // If the operation can be done in a smaller type, do so. 1454 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1455 return true; 1456 1457 // Attempt to avoid multi-use ops if we don't need anything from them. 1458 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1459 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1460 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1461 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1462 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1463 if (DemandedOp0 || DemandedOp1) { 1464 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1465 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1466 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1467 return TLO.CombineTo(Op, NewOp); 1468 } 1469 } 1470 1471 Known |= Known2; 1472 break; 1473 } 1474 case ISD::XOR: { 1475 SDValue Op0 = Op.getOperand(0); 1476 SDValue Op1 = Op.getOperand(1); 1477 1478 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1479 Depth + 1)) 1480 return true; 1481 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1482 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1483 Depth + 1)) 1484 return true; 1485 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1486 1487 // If all of the demanded bits are known zero on one side, return the other. 1488 // These bits cannot contribute to the result of the 'xor'. 1489 if (DemandedBits.isSubsetOf(Known.Zero)) 1490 return TLO.CombineTo(Op, Op0); 1491 if (DemandedBits.isSubsetOf(Known2.Zero)) 1492 return TLO.CombineTo(Op, Op1); 1493 // If the operation can be done in a smaller type, do so. 1494 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1495 return true; 1496 1497 // If all of the unknown bits are known to be zero on one side or the other 1498 // turn this into an *inclusive* or. 1499 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1500 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1501 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1502 1503 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts); 1504 if (C) { 1505 // If one side is a constant, and all of the set bits in the constant are 1506 // also known set on the other side, turn this into an AND, as we know 1507 // the bits will be cleared. 1508 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1509 // NB: it is okay if more bits are known than are requested 1510 if (C->getAPIntValue() == Known2.One) { 1511 SDValue ANDC = 1512 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1513 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1514 } 1515 1516 // If the RHS is a constant, see if we can change it. Don't alter a -1 1517 // constant because that's a 'not' op, and that is better for combining 1518 // and codegen. 1519 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1520 // We're flipping all demanded bits. Flip the undemanded bits too. 1521 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1522 return TLO.CombineTo(Op, New); 1523 } 1524 1525 unsigned Op0Opcode = Op0.getOpcode(); 1526 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) { 1527 if (ConstantSDNode *ShiftC = 1528 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) { 1529 // Don't crash on an oversized shift. We can not guarantee that a 1530 // bogus shift has been simplified to undef. 1531 if (ShiftC->getAPIntValue().ult(BitWidth)) { 1532 uint64_t ShiftAmt = ShiftC->getZExtValue(); 1533 APInt Ones = APInt::getAllOnes(BitWidth); 1534 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) 1535 : Ones.lshr(ShiftAmt); 1536 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 1537 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) && 1538 TLI.isDesirableToCommuteXorWithShift(Op.getNode())) { 1539 // If the xor constant is a demanded mask, do a 'not' before the 1540 // shift: 1541 // xor (X << ShiftC), XorC --> (not X) << ShiftC 1542 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 1543 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT); 1544 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not, 1545 Op0.getOperand(1))); 1546 } 1547 } 1548 } 1549 } 1550 } 1551 1552 // If we can't turn this into a 'not', try to shrink the constant. 1553 if (!C || !C->isAllOnes()) 1554 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1555 return true; 1556 1557 // Attempt to avoid multi-use ops if we don't need anything from them. 1558 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1559 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1560 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1561 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1562 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1563 if (DemandedOp0 || DemandedOp1) { 1564 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1565 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1566 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1567 return TLO.CombineTo(Op, NewOp); 1568 } 1569 } 1570 1571 Known ^= Known2; 1572 break; 1573 } 1574 case ISD::SELECT: 1575 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1576 Depth + 1)) 1577 return true; 1578 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1579 Depth + 1)) 1580 return true; 1581 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1582 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1583 1584 // If the operands are constants, see if we can simplify them. 1585 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1586 return true; 1587 1588 // Only known if known in both the LHS and RHS. 1589 Known = KnownBits::commonBits(Known, Known2); 1590 break; 1591 case ISD::VSELECT: 1592 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1593 Known, TLO, Depth + 1)) 1594 return true; 1595 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1596 Known2, TLO, Depth + 1)) 1597 return true; 1598 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1599 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1600 1601 // Only known if known in both the LHS and RHS. 1602 Known = KnownBits::commonBits(Known, Known2); 1603 break; 1604 case ISD::SELECT_CC: 1605 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1606 Depth + 1)) 1607 return true; 1608 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1609 Depth + 1)) 1610 return true; 1611 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1612 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1613 1614 // If the operands are constants, see if we can simplify them. 1615 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1616 return true; 1617 1618 // Only known if known in both the LHS and RHS. 1619 Known = KnownBits::commonBits(Known, Known2); 1620 break; 1621 case ISD::SETCC: { 1622 SDValue Op0 = Op.getOperand(0); 1623 SDValue Op1 = Op.getOperand(1); 1624 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1625 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1626 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1627 // -1, we may be able to bypass the setcc. 1628 if (DemandedBits.isSignMask() && 1629 Op0.getScalarValueSizeInBits() == BitWidth && 1630 getBooleanContents(Op0.getValueType()) == 1631 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1632 // If we're testing X < 0, then this compare isn't needed - just use X! 1633 // FIXME: We're limiting to integer types here, but this should also work 1634 // if we don't care about FP signed-zero. The use of SETLT with FP means 1635 // that we don't care about NaNs. 1636 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1637 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1638 return TLO.CombineTo(Op, Op0); 1639 1640 // TODO: Should we check for other forms of sign-bit comparisons? 1641 // Examples: X <= -1, X >= 0 1642 } 1643 if (getBooleanContents(Op0.getValueType()) == 1644 TargetLowering::ZeroOrOneBooleanContent && 1645 BitWidth > 1) 1646 Known.Zero.setBitsFrom(1); 1647 break; 1648 } 1649 case ISD::SHL: { 1650 SDValue Op0 = Op.getOperand(0); 1651 SDValue Op1 = Op.getOperand(1); 1652 EVT ShiftVT = Op1.getValueType(); 1653 1654 if (const APInt *SA = 1655 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1656 unsigned ShAmt = SA->getZExtValue(); 1657 if (ShAmt == 0) 1658 return TLO.CombineTo(Op, Op0); 1659 1660 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1661 // single shift. We can do this if the bottom bits (which are shifted 1662 // out) are never demanded. 1663 // TODO - support non-uniform vector amounts. 1664 if (Op0.getOpcode() == ISD::SRL) { 1665 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1666 if (const APInt *SA2 = 1667 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1668 unsigned C1 = SA2->getZExtValue(); 1669 unsigned Opc = ISD::SHL; 1670 int Diff = ShAmt - C1; 1671 if (Diff < 0) { 1672 Diff = -Diff; 1673 Opc = ISD::SRL; 1674 } 1675 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1676 return TLO.CombineTo( 1677 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1678 } 1679 } 1680 } 1681 1682 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1683 // are not demanded. This will likely allow the anyext to be folded away. 1684 // TODO - support non-uniform vector amounts. 1685 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1686 SDValue InnerOp = Op0.getOperand(0); 1687 EVT InnerVT = InnerOp.getValueType(); 1688 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1689 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1690 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1691 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1692 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1693 ShTy = InnerVT; 1694 SDValue NarrowShl = 1695 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1696 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1697 return TLO.CombineTo( 1698 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1699 } 1700 1701 // Repeat the SHL optimization above in cases where an extension 1702 // intervenes: (shl (anyext (shr x, c1)), c2) to 1703 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1704 // aren't demanded (as above) and that the shifted upper c1 bits of 1705 // x aren't demanded. 1706 // TODO - support non-uniform vector amounts. 1707 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1708 InnerOp.hasOneUse()) { 1709 if (const APInt *SA2 = 1710 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1711 unsigned InnerShAmt = SA2->getZExtValue(); 1712 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1713 DemandedBits.getActiveBits() <= 1714 (InnerBits - InnerShAmt + ShAmt) && 1715 DemandedBits.countTrailingZeros() >= ShAmt) { 1716 SDValue NewSA = 1717 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1718 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1719 InnerOp.getOperand(0)); 1720 return TLO.CombineTo( 1721 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1722 } 1723 } 1724 } 1725 } 1726 1727 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1728 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1729 Depth + 1)) 1730 return true; 1731 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1732 Known.Zero <<= ShAmt; 1733 Known.One <<= ShAmt; 1734 // low bits known zero. 1735 Known.Zero.setLowBits(ShAmt); 1736 1737 // Attempt to avoid multi-use ops if we don't need anything from them. 1738 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1739 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1740 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1741 if (DemandedOp0) { 1742 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1743 return TLO.CombineTo(Op, NewOp); 1744 } 1745 } 1746 1747 // Try shrinking the operation as long as the shift amount will still be 1748 // in range. 1749 if ((ShAmt < DemandedBits.getActiveBits()) && 1750 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1751 return true; 1752 } else { 1753 // This is a variable shift, so we can't shift the demand mask by a known 1754 // amount. But if we are not demanding high bits, then we are not 1755 // demanding those bits from the pre-shifted operand either. 1756 if (unsigned CTLZ = DemandedBits.countLeadingZeros()) { 1757 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1758 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1759 Depth + 1)) { 1760 SDNodeFlags Flags = Op.getNode()->getFlags(); 1761 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1762 // Disable the nsw and nuw flags. We can no longer guarantee that we 1763 // won't wrap after simplification. 1764 Flags.setNoSignedWrap(false); 1765 Flags.setNoUnsignedWrap(false); 1766 Op->setFlags(Flags); 1767 } 1768 return true; 1769 } 1770 Known.resetAll(); 1771 } 1772 } 1773 1774 // If we are only demanding sign bits then we can use the shift source 1775 // directly. 1776 if (const APInt *MaxSA = 1777 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1778 unsigned ShAmt = MaxSA->getZExtValue(); 1779 unsigned NumSignBits = 1780 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1781 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1782 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1783 return TLO.CombineTo(Op, Op0); 1784 } 1785 break; 1786 } 1787 case ISD::SRL: { 1788 SDValue Op0 = Op.getOperand(0); 1789 SDValue Op1 = Op.getOperand(1); 1790 EVT ShiftVT = Op1.getValueType(); 1791 1792 // Try to match AVG patterns. 1793 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1794 DemandedElts, Depth + 1)) 1795 return TLO.CombineTo(Op, AVG); 1796 1797 if (const APInt *SA = 1798 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1799 unsigned ShAmt = SA->getZExtValue(); 1800 if (ShAmt == 0) 1801 return TLO.CombineTo(Op, Op0); 1802 1803 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1804 // single shift. We can do this if the top bits (which are shifted out) 1805 // are never demanded. 1806 // TODO - support non-uniform vector amounts. 1807 if (Op0.getOpcode() == ISD::SHL) { 1808 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1809 if (const APInt *SA2 = 1810 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1811 unsigned C1 = SA2->getZExtValue(); 1812 unsigned Opc = ISD::SRL; 1813 int Diff = ShAmt - C1; 1814 if (Diff < 0) { 1815 Diff = -Diff; 1816 Opc = ISD::SHL; 1817 } 1818 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1819 return TLO.CombineTo( 1820 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1821 } 1822 } 1823 } 1824 1825 APInt InDemandedMask = (DemandedBits << ShAmt); 1826 1827 // If the shift is exact, then it does demand the low bits (and knows that 1828 // they are zero). 1829 if (Op->getFlags().hasExact()) 1830 InDemandedMask.setLowBits(ShAmt); 1831 1832 // Compute the new bits that are at the top now. 1833 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1834 Depth + 1)) 1835 return true; 1836 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1837 Known.Zero.lshrInPlace(ShAmt); 1838 Known.One.lshrInPlace(ShAmt); 1839 // High bits known zero. 1840 Known.Zero.setHighBits(ShAmt); 1841 } 1842 break; 1843 } 1844 case ISD::SRA: { 1845 SDValue Op0 = Op.getOperand(0); 1846 SDValue Op1 = Op.getOperand(1); 1847 EVT ShiftVT = Op1.getValueType(); 1848 1849 // If we only want bits that already match the signbit then we don't need 1850 // to shift. 1851 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1852 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1853 NumHiDemandedBits) 1854 return TLO.CombineTo(Op, Op0); 1855 1856 // If this is an arithmetic shift right and only the low-bit is set, we can 1857 // always convert this into a logical shr, even if the shift amount is 1858 // variable. The low bit of the shift cannot be an input sign bit unless 1859 // the shift amount is >= the size of the datatype, which is undefined. 1860 if (DemandedBits.isOne()) 1861 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1862 1863 // Try to match AVG patterns. 1864 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1865 DemandedElts, Depth + 1)) 1866 return TLO.CombineTo(Op, AVG); 1867 1868 if (const APInt *SA = 1869 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1870 unsigned ShAmt = SA->getZExtValue(); 1871 if (ShAmt == 0) 1872 return TLO.CombineTo(Op, Op0); 1873 1874 APInt InDemandedMask = (DemandedBits << ShAmt); 1875 1876 // If the shift is exact, then it does demand the low bits (and knows that 1877 // they are zero). 1878 if (Op->getFlags().hasExact()) 1879 InDemandedMask.setLowBits(ShAmt); 1880 1881 // If any of the demanded bits are produced by the sign extension, we also 1882 // demand the input sign bit. 1883 if (DemandedBits.countLeadingZeros() < ShAmt) 1884 InDemandedMask.setSignBit(); 1885 1886 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1887 Depth + 1)) 1888 return true; 1889 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1890 Known.Zero.lshrInPlace(ShAmt); 1891 Known.One.lshrInPlace(ShAmt); 1892 1893 // If the input sign bit is known to be zero, or if none of the top bits 1894 // are demanded, turn this into an unsigned shift right. 1895 if (Known.Zero[BitWidth - ShAmt - 1] || 1896 DemandedBits.countLeadingZeros() >= ShAmt) { 1897 SDNodeFlags Flags; 1898 Flags.setExact(Op->getFlags().hasExact()); 1899 return TLO.CombineTo( 1900 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1901 } 1902 1903 int Log2 = DemandedBits.exactLogBase2(); 1904 if (Log2 >= 0) { 1905 // The bit must come from the sign. 1906 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1907 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1908 } 1909 1910 if (Known.One[BitWidth - ShAmt - 1]) 1911 // New bits are known one. 1912 Known.One.setHighBits(ShAmt); 1913 1914 // Attempt to avoid multi-use ops if we don't need anything from them. 1915 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1916 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1917 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1918 if (DemandedOp0) { 1919 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1920 return TLO.CombineTo(Op, NewOp); 1921 } 1922 } 1923 } 1924 break; 1925 } 1926 case ISD::FSHL: 1927 case ISD::FSHR: { 1928 SDValue Op0 = Op.getOperand(0); 1929 SDValue Op1 = Op.getOperand(1); 1930 SDValue Op2 = Op.getOperand(2); 1931 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1932 1933 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1934 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1935 1936 // For fshl, 0-shift returns the 1st arg. 1937 // For fshr, 0-shift returns the 2nd arg. 1938 if (Amt == 0) { 1939 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1940 Known, TLO, Depth + 1)) 1941 return true; 1942 break; 1943 } 1944 1945 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1946 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1947 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1948 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1949 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1950 Depth + 1)) 1951 return true; 1952 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1953 Depth + 1)) 1954 return true; 1955 1956 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1957 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1958 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1959 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1960 Known.One |= Known2.One; 1961 Known.Zero |= Known2.Zero; 1962 1963 // Attempt to avoid multi-use ops if we don't need anything from them. 1964 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 1965 !DemandedElts.isAllOnes()) { 1966 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1967 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 1968 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1969 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 1970 if (DemandedOp0 || DemandedOp1) { 1971 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 1972 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 1973 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 1974 DemandedOp1, Op2); 1975 return TLO.CombineTo(Op, NewOp); 1976 } 1977 } 1978 } 1979 1980 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1981 if (isPowerOf2_32(BitWidth)) { 1982 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1983 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1984 Known2, TLO, Depth + 1)) 1985 return true; 1986 } 1987 break; 1988 } 1989 case ISD::ROTL: 1990 case ISD::ROTR: { 1991 SDValue Op0 = Op.getOperand(0); 1992 SDValue Op1 = Op.getOperand(1); 1993 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1994 1995 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1996 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1997 return TLO.CombineTo(Op, Op0); 1998 1999 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 2000 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2001 unsigned RevAmt = BitWidth - Amt; 2002 2003 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 2004 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 2005 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 2006 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2007 Depth + 1)) 2008 return true; 2009 2010 // rot*(x, 0) --> x 2011 if (Amt == 0) 2012 return TLO.CombineTo(Op, Op0); 2013 2014 // See if we don't demand either half of the rotated bits. 2015 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 2016 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 2017 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 2018 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 2019 } 2020 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 2021 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 2022 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 2023 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2024 } 2025 } 2026 2027 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2028 if (isPowerOf2_32(BitWidth)) { 2029 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2030 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2031 Depth + 1)) 2032 return true; 2033 } 2034 break; 2035 } 2036 case ISD::UMIN: { 2037 // Check if one arg is always less than (or equal) to the other arg. 2038 SDValue Op0 = Op.getOperand(0); 2039 SDValue Op1 = Op.getOperand(1); 2040 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2041 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2042 Known = KnownBits::umin(Known0, Known1); 2043 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2044 return TLO.CombineTo(Op, IsULE.value() ? Op0 : Op1); 2045 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2046 return TLO.CombineTo(Op, IsULT.value() ? Op0 : Op1); 2047 break; 2048 } 2049 case ISD::UMAX: { 2050 // Check if one arg is always greater than (or equal) to the other arg. 2051 SDValue Op0 = Op.getOperand(0); 2052 SDValue Op1 = Op.getOperand(1); 2053 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2054 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2055 Known = KnownBits::umax(Known0, Known1); 2056 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2057 return TLO.CombineTo(Op, IsUGE.value() ? Op0 : Op1); 2058 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2059 return TLO.CombineTo(Op, IsUGT.value() ? Op0 : Op1); 2060 break; 2061 } 2062 case ISD::BITREVERSE: { 2063 SDValue Src = Op.getOperand(0); 2064 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2065 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2066 Depth + 1)) 2067 return true; 2068 Known.One = Known2.One.reverseBits(); 2069 Known.Zero = Known2.Zero.reverseBits(); 2070 break; 2071 } 2072 case ISD::BSWAP: { 2073 SDValue Src = Op.getOperand(0); 2074 2075 // If the only bits demanded come from one byte of the bswap result, 2076 // just shift the input byte into position to eliminate the bswap. 2077 unsigned NLZ = DemandedBits.countLeadingZeros(); 2078 unsigned NTZ = DemandedBits.countTrailingZeros(); 2079 2080 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2081 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2082 // have 14 leading zeros, round to 8. 2083 NLZ = alignDown(NLZ, 8); 2084 NTZ = alignDown(NTZ, 8); 2085 // If we need exactly one byte, we can do this transformation. 2086 if (BitWidth - NLZ - NTZ == 8) { 2087 // Replace this with either a left or right shift to get the byte into 2088 // the right place. 2089 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2090 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2091 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2092 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2093 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2094 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2095 return TLO.CombineTo(Op, NewOp); 2096 } 2097 } 2098 2099 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2100 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2101 Depth + 1)) 2102 return true; 2103 Known.One = Known2.One.byteSwap(); 2104 Known.Zero = Known2.Zero.byteSwap(); 2105 break; 2106 } 2107 case ISD::CTPOP: { 2108 // If only 1 bit is demanded, replace with PARITY as long as we're before 2109 // op legalization. 2110 // FIXME: Limit to scalars for now. 2111 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2112 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2113 Op.getOperand(0))); 2114 2115 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2116 break; 2117 } 2118 case ISD::SIGN_EXTEND_INREG: { 2119 SDValue Op0 = Op.getOperand(0); 2120 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2121 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2122 2123 // If we only care about the highest bit, don't bother shifting right. 2124 if (DemandedBits.isSignMask()) { 2125 unsigned MinSignedBits = 2126 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2127 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2128 // However if the input is already sign extended we expect the sign 2129 // extension to be dropped altogether later and do not simplify. 2130 if (!AlreadySignExtended) { 2131 // Compute the correct shift amount type, which must be getShiftAmountTy 2132 // for scalar types after legalization. 2133 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2134 getShiftAmountTy(VT, DL)); 2135 return TLO.CombineTo(Op, 2136 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2137 } 2138 } 2139 2140 // If none of the extended bits are demanded, eliminate the sextinreg. 2141 if (DemandedBits.getActiveBits() <= ExVTBits) 2142 return TLO.CombineTo(Op, Op0); 2143 2144 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2145 2146 // Since the sign extended bits are demanded, we know that the sign 2147 // bit is demanded. 2148 InputDemandedBits.setBit(ExVTBits - 1); 2149 2150 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2151 Depth + 1)) 2152 return true; 2153 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2154 2155 // If the sign bit of the input is known set or clear, then we know the 2156 // top bits of the result. 2157 2158 // If the input sign bit is known zero, convert this into a zero extension. 2159 if (Known.Zero[ExVTBits - 1]) 2160 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2161 2162 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2163 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2164 Known.One.setBitsFrom(ExVTBits); 2165 Known.Zero &= Mask; 2166 } else { // Input sign bit unknown 2167 Known.Zero &= Mask; 2168 Known.One &= Mask; 2169 } 2170 break; 2171 } 2172 case ISD::BUILD_PAIR: { 2173 EVT HalfVT = Op.getOperand(0).getValueType(); 2174 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2175 2176 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2177 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2178 2179 KnownBits KnownLo, KnownHi; 2180 2181 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2182 return true; 2183 2184 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2185 return true; 2186 2187 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2188 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2189 2190 Known.One = KnownLo.One.zext(BitWidth) | 2191 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2192 break; 2193 } 2194 case ISD::ZERO_EXTEND: 2195 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2196 SDValue Src = Op.getOperand(0); 2197 EVT SrcVT = Src.getValueType(); 2198 unsigned InBits = SrcVT.getScalarSizeInBits(); 2199 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2200 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2201 2202 // If none of the top bits are demanded, convert this into an any_extend. 2203 if (DemandedBits.getActiveBits() <= InBits) { 2204 // If we only need the non-extended bits of the bottom element 2205 // then we can just bitcast to the result. 2206 if (IsLE && IsVecInReg && DemandedElts == 1 && 2207 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2208 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2209 2210 unsigned Opc = 2211 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2212 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2213 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2214 } 2215 2216 APInt InDemandedBits = DemandedBits.trunc(InBits); 2217 APInt InDemandedElts = DemandedElts.zext(InElts); 2218 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2219 Depth + 1)) 2220 return true; 2221 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2222 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2223 Known = Known.zext(BitWidth); 2224 2225 // Attempt to avoid multi-use ops if we don't need anything from them. 2226 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2227 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2228 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2229 break; 2230 } 2231 case ISD::SIGN_EXTEND: 2232 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2233 SDValue Src = Op.getOperand(0); 2234 EVT SrcVT = Src.getValueType(); 2235 unsigned InBits = SrcVT.getScalarSizeInBits(); 2236 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2237 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2238 2239 // If none of the top bits are demanded, convert this into an any_extend. 2240 if (DemandedBits.getActiveBits() <= InBits) { 2241 // If we only need the non-extended bits of the bottom element 2242 // then we can just bitcast to the result. 2243 if (IsLE && IsVecInReg && DemandedElts == 1 && 2244 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2245 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2246 2247 unsigned Opc = 2248 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2249 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2250 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2251 } 2252 2253 APInt InDemandedBits = DemandedBits.trunc(InBits); 2254 APInt InDemandedElts = DemandedElts.zext(InElts); 2255 2256 // Since some of the sign extended bits are demanded, we know that the sign 2257 // bit is demanded. 2258 InDemandedBits.setBit(InBits - 1); 2259 2260 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2261 Depth + 1)) 2262 return true; 2263 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2264 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2265 2266 // If the sign bit is known one, the top bits match. 2267 Known = Known.sext(BitWidth); 2268 2269 // If the sign bit is known zero, convert this to a zero extend. 2270 if (Known.isNonNegative()) { 2271 unsigned Opc = 2272 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2273 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2274 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2275 } 2276 2277 // Attempt to avoid multi-use ops if we don't need anything from them. 2278 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2279 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2280 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2281 break; 2282 } 2283 case ISD::ANY_EXTEND: 2284 case ISD::ANY_EXTEND_VECTOR_INREG: { 2285 SDValue Src = Op.getOperand(0); 2286 EVT SrcVT = Src.getValueType(); 2287 unsigned InBits = SrcVT.getScalarSizeInBits(); 2288 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2289 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2290 2291 // If we only need the bottom element then we can just bitcast. 2292 // TODO: Handle ANY_EXTEND? 2293 if (IsLE && IsVecInReg && DemandedElts == 1 && 2294 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2295 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2296 2297 APInt InDemandedBits = DemandedBits.trunc(InBits); 2298 APInt InDemandedElts = DemandedElts.zext(InElts); 2299 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2300 Depth + 1)) 2301 return true; 2302 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2303 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2304 Known = Known.anyext(BitWidth); 2305 2306 // Attempt to avoid multi-use ops if we don't need anything from them. 2307 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2308 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2309 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2310 break; 2311 } 2312 case ISD::TRUNCATE: { 2313 SDValue Src = Op.getOperand(0); 2314 2315 // Simplify the input, using demanded bit information, and compute the known 2316 // zero/one bits live out. 2317 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2318 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2319 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2320 Depth + 1)) 2321 return true; 2322 Known = Known.trunc(BitWidth); 2323 2324 // Attempt to avoid multi-use ops if we don't need anything from them. 2325 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2326 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2327 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2328 2329 // If the input is only used by this truncate, see if we can shrink it based 2330 // on the known demanded bits. 2331 if (Src.getNode()->hasOneUse()) { 2332 switch (Src.getOpcode()) { 2333 default: 2334 break; 2335 case ISD::SRL: 2336 // Shrink SRL by a constant if none of the high bits shifted in are 2337 // demanded. 2338 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2339 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2340 // undesirable. 2341 break; 2342 2343 const APInt *ShAmtC = 2344 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2345 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2346 break; 2347 uint64_t ShVal = ShAmtC->getZExtValue(); 2348 2349 APInt HighBits = 2350 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2351 HighBits.lshrInPlace(ShVal); 2352 HighBits = HighBits.trunc(BitWidth); 2353 2354 if (!(HighBits & DemandedBits)) { 2355 // None of the shifted in bits are needed. Add a truncate of the 2356 // shift input, then shift it. 2357 SDValue NewShAmt = TLO.DAG.getConstant( 2358 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2359 SDValue NewTrunc = 2360 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2361 return TLO.CombineTo( 2362 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2363 } 2364 break; 2365 } 2366 } 2367 2368 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2369 break; 2370 } 2371 case ISD::AssertZext: { 2372 // AssertZext demands all of the high bits, plus any of the low bits 2373 // demanded by its users. 2374 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2375 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2376 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2377 TLO, Depth + 1)) 2378 return true; 2379 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2380 2381 Known.Zero |= ~InMask; 2382 break; 2383 } 2384 case ISD::EXTRACT_VECTOR_ELT: { 2385 SDValue Src = Op.getOperand(0); 2386 SDValue Idx = Op.getOperand(1); 2387 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2388 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2389 2390 if (SrcEltCnt.isScalable()) 2391 return false; 2392 2393 // Demand the bits from every vector element without a constant index. 2394 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2395 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2396 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2397 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2398 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2399 2400 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2401 // anything about the extended bits. 2402 APInt DemandedSrcBits = DemandedBits; 2403 if (BitWidth > EltBitWidth) 2404 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2405 2406 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2407 Depth + 1)) 2408 return true; 2409 2410 // Attempt to avoid multi-use ops if we don't need anything from them. 2411 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2412 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2413 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2414 SDValue NewOp = 2415 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2416 return TLO.CombineTo(Op, NewOp); 2417 } 2418 } 2419 2420 Known = Known2; 2421 if (BitWidth > EltBitWidth) 2422 Known = Known.anyext(BitWidth); 2423 break; 2424 } 2425 case ISD::BITCAST: { 2426 SDValue Src = Op.getOperand(0); 2427 EVT SrcVT = Src.getValueType(); 2428 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2429 2430 // If this is an FP->Int bitcast and if the sign bit is the only 2431 // thing demanded, turn this into a FGETSIGN. 2432 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2433 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2434 SrcVT.isFloatingPoint()) { 2435 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2436 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2437 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2438 SrcVT != MVT::f128) { 2439 // Cannot eliminate/lower SHL for f128 yet. 2440 EVT Ty = OpVTLegal ? VT : MVT::i32; 2441 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2442 // place. We expect the SHL to be eliminated by other optimizations. 2443 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2444 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2445 if (!OpVTLegal && OpVTSizeInBits > 32) 2446 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2447 unsigned ShVal = Op.getValueSizeInBits() - 1; 2448 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2449 return TLO.CombineTo(Op, 2450 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2451 } 2452 } 2453 2454 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2455 // Demand the elt/bit if any of the original elts/bits are demanded. 2456 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2457 unsigned Scale = BitWidth / NumSrcEltBits; 2458 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2459 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2460 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2461 for (unsigned i = 0; i != Scale; ++i) { 2462 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2463 unsigned BitOffset = EltOffset * NumSrcEltBits; 2464 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2465 if (!Sub.isZero()) { 2466 DemandedSrcBits |= Sub; 2467 for (unsigned j = 0; j != NumElts; ++j) 2468 if (DemandedElts[j]) 2469 DemandedSrcElts.setBit((j * Scale) + i); 2470 } 2471 } 2472 2473 APInt KnownSrcUndef, KnownSrcZero; 2474 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2475 KnownSrcZero, TLO, Depth + 1)) 2476 return true; 2477 2478 KnownBits KnownSrcBits; 2479 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2480 KnownSrcBits, TLO, Depth + 1)) 2481 return true; 2482 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2483 // TODO - bigendian once we have test coverage. 2484 unsigned Scale = NumSrcEltBits / BitWidth; 2485 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2486 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2487 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2488 for (unsigned i = 0; i != NumElts; ++i) 2489 if (DemandedElts[i]) { 2490 unsigned Offset = (i % Scale) * BitWidth; 2491 DemandedSrcBits.insertBits(DemandedBits, Offset); 2492 DemandedSrcElts.setBit(i / Scale); 2493 } 2494 2495 if (SrcVT.isVector()) { 2496 APInt KnownSrcUndef, KnownSrcZero; 2497 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2498 KnownSrcZero, TLO, Depth + 1)) 2499 return true; 2500 } 2501 2502 KnownBits KnownSrcBits; 2503 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2504 KnownSrcBits, TLO, Depth + 1)) 2505 return true; 2506 } 2507 2508 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2509 // recursive call where Known may be useful to the caller. 2510 if (Depth > 0) { 2511 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2512 return false; 2513 } 2514 break; 2515 } 2516 case ISD::MUL: 2517 if (DemandedBits.isPowerOf2()) { 2518 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2519 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2520 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2521 unsigned CTZ = DemandedBits.countTrailingZeros(); 2522 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2523 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2524 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2525 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2526 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2527 return TLO.CombineTo(Op, Shl); 2528 } 2529 } 2530 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2531 // X * X is odd iff X is odd. 2532 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2533 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2534 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2535 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2536 return TLO.CombineTo(Op, And1); 2537 } 2538 LLVM_FALLTHROUGH; 2539 case ISD::ADD: 2540 case ISD::SUB: { 2541 // Add, Sub, and Mul don't demand any bits in positions beyond that 2542 // of the highest bit demanded of them. 2543 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2544 SDNodeFlags Flags = Op.getNode()->getFlags(); 2545 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2546 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2547 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2548 Depth + 1) || 2549 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2550 Depth + 1) || 2551 // See if the operation should be performed at a smaller bit width. 2552 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2553 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2554 // Disable the nsw and nuw flags. We can no longer guarantee that we 2555 // won't wrap after simplification. 2556 Flags.setNoSignedWrap(false); 2557 Flags.setNoUnsignedWrap(false); 2558 Op->setFlags(Flags); 2559 } 2560 return true; 2561 } 2562 2563 // Attempt to avoid multi-use ops if we don't need anything from them. 2564 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2565 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2566 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2567 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2568 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2569 if (DemandedOp0 || DemandedOp1) { 2570 Flags.setNoSignedWrap(false); 2571 Flags.setNoUnsignedWrap(false); 2572 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2573 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2574 SDValue NewOp = 2575 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2576 return TLO.CombineTo(Op, NewOp); 2577 } 2578 } 2579 2580 // If we have a constant operand, we may be able to turn it into -1 if we 2581 // do not demand the high bits. This can make the constant smaller to 2582 // encode, allow more general folding, or match specialized instruction 2583 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2584 // is probably not useful (and could be detrimental). 2585 ConstantSDNode *C = isConstOrConstSplat(Op1); 2586 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2587 if (C && !C->isAllOnes() && !C->isOne() && 2588 (C->getAPIntValue() | HighMask).isAllOnes()) { 2589 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2590 // Disable the nsw and nuw flags. We can no longer guarantee that we 2591 // won't wrap after simplification. 2592 Flags.setNoSignedWrap(false); 2593 Flags.setNoUnsignedWrap(false); 2594 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2595 return TLO.CombineTo(Op, NewOp); 2596 } 2597 2598 // Match a multiply with a disguised negated-power-of-2 and convert to a 2599 // an equivalent shift-left amount. 2600 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2601 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2602 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2603 return 0; 2604 2605 // Don't touch opaque constants. Also, ignore zero and power-of-2 2606 // multiplies. Those will get folded later. 2607 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2608 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2609 !MulC->getAPIntValue().isPowerOf2()) { 2610 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2611 if (UnmaskedC.isNegatedPowerOf2()) 2612 return (-UnmaskedC).logBase2(); 2613 } 2614 return 0; 2615 }; 2616 2617 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) { 2618 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2619 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2620 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2621 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2622 return TLO.CombineTo(Op, Res); 2623 }; 2624 2625 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2626 if (Op.getOpcode() == ISD::ADD) { 2627 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2628 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2629 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2630 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2631 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2632 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2633 } 2634 if (Op.getOpcode() == ISD::SUB) { 2635 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2636 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2637 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2638 } 2639 } 2640 2641 LLVM_FALLTHROUGH; 2642 } 2643 default: 2644 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2645 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2646 Known, TLO, Depth)) 2647 return true; 2648 break; 2649 } 2650 2651 // Just use computeKnownBits to compute output bits. 2652 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2653 break; 2654 } 2655 2656 // If we know the value of all of the demanded bits, return this as a 2657 // constant. 2658 if (!isTargetCanonicalConstantNode(Op) && 2659 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2660 // Avoid folding to a constant if any OpaqueConstant is involved. 2661 const SDNode *N = Op.getNode(); 2662 for (SDNode *Op : 2663 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2664 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2665 if (C->isOpaque()) 2666 return false; 2667 } 2668 if (VT.isInteger()) 2669 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2670 if (VT.isFloatingPoint()) 2671 return TLO.CombineTo( 2672 Op, 2673 TLO.DAG.getConstantFP( 2674 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2675 } 2676 2677 return false; 2678 } 2679 2680 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2681 const APInt &DemandedElts, 2682 DAGCombinerInfo &DCI) const { 2683 SelectionDAG &DAG = DCI.DAG; 2684 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2685 !DCI.isBeforeLegalizeOps()); 2686 2687 APInt KnownUndef, KnownZero; 2688 bool Simplified = 2689 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2690 if (Simplified) { 2691 DCI.AddToWorklist(Op.getNode()); 2692 DCI.CommitTargetLoweringOpt(TLO); 2693 } 2694 2695 return Simplified; 2696 } 2697 2698 /// Given a vector binary operation and known undefined elements for each input 2699 /// operand, compute whether each element of the output is undefined. 2700 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2701 const APInt &UndefOp0, 2702 const APInt &UndefOp1) { 2703 EVT VT = BO.getValueType(); 2704 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2705 "Vector binop only"); 2706 2707 EVT EltVT = VT.getVectorElementType(); 2708 unsigned NumElts = VT.getVectorNumElements(); 2709 assert(UndefOp0.getBitWidth() == NumElts && 2710 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2711 2712 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2713 const APInt &UndefVals) { 2714 if (UndefVals[Index]) 2715 return DAG.getUNDEF(EltVT); 2716 2717 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2718 // Try hard to make sure that the getNode() call is not creating temporary 2719 // nodes. Ignore opaque integers because they do not constant fold. 2720 SDValue Elt = BV->getOperand(Index); 2721 auto *C = dyn_cast<ConstantSDNode>(Elt); 2722 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2723 return Elt; 2724 } 2725 2726 return SDValue(); 2727 }; 2728 2729 APInt KnownUndef = APInt::getZero(NumElts); 2730 for (unsigned i = 0; i != NumElts; ++i) { 2731 // If both inputs for this element are either constant or undef and match 2732 // the element type, compute the constant/undef result for this element of 2733 // the vector. 2734 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2735 // not handle FP constants. The code within getNode() should be refactored 2736 // to avoid the danger of creating a bogus temporary node here. 2737 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2738 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2739 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2740 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2741 KnownUndef.setBit(i); 2742 } 2743 return KnownUndef; 2744 } 2745 2746 bool TargetLowering::SimplifyDemandedVectorElts( 2747 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2748 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2749 bool AssumeSingleUse) const { 2750 EVT VT = Op.getValueType(); 2751 unsigned Opcode = Op.getOpcode(); 2752 APInt DemandedElts = OriginalDemandedElts; 2753 unsigned NumElts = DemandedElts.getBitWidth(); 2754 assert(VT.isVector() && "Expected vector op"); 2755 2756 KnownUndef = KnownZero = APInt::getZero(NumElts); 2757 2758 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2759 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2760 return false; 2761 2762 // TODO: For now we assume we know nothing about scalable vectors. 2763 if (VT.isScalableVector()) 2764 return false; 2765 2766 assert(VT.getVectorNumElements() == NumElts && 2767 "Mask size mismatches value type element count!"); 2768 2769 // Undef operand. 2770 if (Op.isUndef()) { 2771 KnownUndef.setAllBits(); 2772 return false; 2773 } 2774 2775 // If Op has other users, assume that all elements are needed. 2776 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2777 DemandedElts.setAllBits(); 2778 2779 // Not demanding any elements from Op. 2780 if (DemandedElts == 0) { 2781 KnownUndef.setAllBits(); 2782 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2783 } 2784 2785 // Limit search depth. 2786 if (Depth >= SelectionDAG::MaxRecursionDepth) 2787 return false; 2788 2789 SDLoc DL(Op); 2790 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2791 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2792 2793 // Helper for demanding the specified elements and all the bits of both binary 2794 // operands. 2795 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2796 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2797 TLO.DAG, Depth + 1); 2798 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2799 TLO.DAG, Depth + 1); 2800 if (NewOp0 || NewOp1) { 2801 SDValue NewOp = TLO.DAG.getNode( 2802 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2803 return TLO.CombineTo(Op, NewOp); 2804 } 2805 return false; 2806 }; 2807 2808 switch (Opcode) { 2809 case ISD::SCALAR_TO_VECTOR: { 2810 if (!DemandedElts[0]) { 2811 KnownUndef.setAllBits(); 2812 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2813 } 2814 SDValue ScalarSrc = Op.getOperand(0); 2815 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2816 SDValue Src = ScalarSrc.getOperand(0); 2817 SDValue Idx = ScalarSrc.getOperand(1); 2818 EVT SrcVT = Src.getValueType(); 2819 2820 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2821 2822 if (SrcEltCnt.isScalable()) 2823 return false; 2824 2825 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2826 if (isNullConstant(Idx)) { 2827 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2828 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2829 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2830 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2831 TLO, Depth + 1)) 2832 return true; 2833 } 2834 } 2835 KnownUndef.setHighBits(NumElts - 1); 2836 break; 2837 } 2838 case ISD::BITCAST: { 2839 SDValue Src = Op.getOperand(0); 2840 EVT SrcVT = Src.getValueType(); 2841 2842 // We only handle vectors here. 2843 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2844 if (!SrcVT.isVector()) 2845 break; 2846 2847 // Fast handling of 'identity' bitcasts. 2848 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2849 if (NumSrcElts == NumElts) 2850 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2851 KnownZero, TLO, Depth + 1); 2852 2853 APInt SrcDemandedElts, SrcZero, SrcUndef; 2854 2855 // Bitcast from 'large element' src vector to 'small element' vector, we 2856 // must demand a source element if any DemandedElt maps to it. 2857 if ((NumElts % NumSrcElts) == 0) { 2858 unsigned Scale = NumElts / NumSrcElts; 2859 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2860 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2861 TLO, Depth + 1)) 2862 return true; 2863 2864 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2865 // of the large element. 2866 // TODO - bigendian once we have test coverage. 2867 if (IsLE) { 2868 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2869 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2870 for (unsigned i = 0; i != NumElts; ++i) 2871 if (DemandedElts[i]) { 2872 unsigned Ofs = (i % Scale) * EltSizeInBits; 2873 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2874 } 2875 2876 KnownBits Known; 2877 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2878 TLO, Depth + 1)) 2879 return true; 2880 2881 // The bitcast has split each wide element into a number of 2882 // narrow subelements. We have just computed the Known bits 2883 // for wide elements. See if element splitting results in 2884 // some subelements being zero. Only for demanded elements! 2885 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2886 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2887 .isAllOnes()) 2888 continue; 2889 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2890 unsigned Elt = Scale * SrcElt + SubElt; 2891 if (DemandedElts[Elt]) 2892 KnownZero.setBit(Elt); 2893 } 2894 } 2895 } 2896 2897 // If the src element is zero/undef then all the output elements will be - 2898 // only demanded elements are guaranteed to be correct. 2899 for (unsigned i = 0; i != NumSrcElts; ++i) { 2900 if (SrcDemandedElts[i]) { 2901 if (SrcZero[i]) 2902 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2903 if (SrcUndef[i]) 2904 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2905 } 2906 } 2907 } 2908 2909 // Bitcast from 'small element' src vector to 'large element' vector, we 2910 // demand all smaller source elements covered by the larger demanded element 2911 // of this vector. 2912 if ((NumSrcElts % NumElts) == 0) { 2913 unsigned Scale = NumSrcElts / NumElts; 2914 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2915 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2916 TLO, Depth + 1)) 2917 return true; 2918 2919 // If all the src elements covering an output element are zero/undef, then 2920 // the output element will be as well, assuming it was demanded. 2921 for (unsigned i = 0; i != NumElts; ++i) { 2922 if (DemandedElts[i]) { 2923 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2924 KnownZero.setBit(i); 2925 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2926 KnownUndef.setBit(i); 2927 } 2928 } 2929 } 2930 break; 2931 } 2932 case ISD::BUILD_VECTOR: { 2933 // Check all elements and simplify any unused elements with UNDEF. 2934 if (!DemandedElts.isAllOnes()) { 2935 // Don't simplify BROADCASTS. 2936 if (llvm::any_of(Op->op_values(), 2937 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2938 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2939 bool Updated = false; 2940 for (unsigned i = 0; i != NumElts; ++i) { 2941 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2942 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2943 KnownUndef.setBit(i); 2944 Updated = true; 2945 } 2946 } 2947 if (Updated) 2948 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2949 } 2950 } 2951 for (unsigned i = 0; i != NumElts; ++i) { 2952 SDValue SrcOp = Op.getOperand(i); 2953 if (SrcOp.isUndef()) { 2954 KnownUndef.setBit(i); 2955 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2956 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2957 KnownZero.setBit(i); 2958 } 2959 } 2960 break; 2961 } 2962 case ISD::CONCAT_VECTORS: { 2963 EVT SubVT = Op.getOperand(0).getValueType(); 2964 unsigned NumSubVecs = Op.getNumOperands(); 2965 unsigned NumSubElts = SubVT.getVectorNumElements(); 2966 for (unsigned i = 0; i != NumSubVecs; ++i) { 2967 SDValue SubOp = Op.getOperand(i); 2968 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2969 APInt SubUndef, SubZero; 2970 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2971 Depth + 1)) 2972 return true; 2973 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2974 KnownZero.insertBits(SubZero, i * NumSubElts); 2975 } 2976 2977 // Attempt to avoid multi-use ops if we don't need anything from them. 2978 if (!DemandedElts.isAllOnes()) { 2979 bool FoundNewSub = false; 2980 SmallVector<SDValue, 2> DemandedSubOps; 2981 for (unsigned i = 0; i != NumSubVecs; ++i) { 2982 SDValue SubOp = Op.getOperand(i); 2983 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2984 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 2985 SubOp, SubElts, TLO.DAG, Depth + 1); 2986 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 2987 FoundNewSub = NewSubOp ? true : FoundNewSub; 2988 } 2989 if (FoundNewSub) { 2990 SDValue NewOp = 2991 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 2992 return TLO.CombineTo(Op, NewOp); 2993 } 2994 } 2995 break; 2996 } 2997 case ISD::INSERT_SUBVECTOR: { 2998 // Demand any elements from the subvector and the remainder from the src its 2999 // inserted into. 3000 SDValue Src = Op.getOperand(0); 3001 SDValue Sub = Op.getOperand(1); 3002 uint64_t Idx = Op.getConstantOperandVal(2); 3003 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3004 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3005 APInt DemandedSrcElts = DemandedElts; 3006 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3007 3008 APInt SubUndef, SubZero; 3009 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 3010 Depth + 1)) 3011 return true; 3012 3013 // If none of the src operand elements are demanded, replace it with undef. 3014 if (!DemandedSrcElts && !Src.isUndef()) 3015 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 3016 TLO.DAG.getUNDEF(VT), Sub, 3017 Op.getOperand(2))); 3018 3019 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 3020 TLO, Depth + 1)) 3021 return true; 3022 KnownUndef.insertBits(SubUndef, Idx); 3023 KnownZero.insertBits(SubZero, Idx); 3024 3025 // Attempt to avoid multi-use ops if we don't need anything from them. 3026 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3027 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3028 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3029 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3030 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3031 if (NewSrc || NewSub) { 3032 NewSrc = NewSrc ? NewSrc : Src; 3033 NewSub = NewSub ? NewSub : Sub; 3034 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3035 NewSub, Op.getOperand(2)); 3036 return TLO.CombineTo(Op, NewOp); 3037 } 3038 } 3039 break; 3040 } 3041 case ISD::EXTRACT_SUBVECTOR: { 3042 // Offset the demanded elts by the subvector index. 3043 SDValue Src = Op.getOperand(0); 3044 if (Src.getValueType().isScalableVector()) 3045 break; 3046 uint64_t Idx = Op.getConstantOperandVal(1); 3047 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3048 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3049 3050 APInt SrcUndef, SrcZero; 3051 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3052 Depth + 1)) 3053 return true; 3054 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3055 KnownZero = SrcZero.extractBits(NumElts, Idx); 3056 3057 // Attempt to avoid multi-use ops if we don't need anything from them. 3058 if (!DemandedElts.isAllOnes()) { 3059 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3060 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3061 if (NewSrc) { 3062 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3063 Op.getOperand(1)); 3064 return TLO.CombineTo(Op, NewOp); 3065 } 3066 } 3067 break; 3068 } 3069 case ISD::INSERT_VECTOR_ELT: { 3070 SDValue Vec = Op.getOperand(0); 3071 SDValue Scl = Op.getOperand(1); 3072 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3073 3074 // For a legal, constant insertion index, if we don't need this insertion 3075 // then strip it, else remove it from the demanded elts. 3076 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3077 unsigned Idx = CIdx->getZExtValue(); 3078 if (!DemandedElts[Idx]) 3079 return TLO.CombineTo(Op, Vec); 3080 3081 APInt DemandedVecElts(DemandedElts); 3082 DemandedVecElts.clearBit(Idx); 3083 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3084 KnownZero, TLO, Depth + 1)) 3085 return true; 3086 3087 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3088 3089 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3090 break; 3091 } 3092 3093 APInt VecUndef, VecZero; 3094 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3095 Depth + 1)) 3096 return true; 3097 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3098 break; 3099 } 3100 case ISD::VSELECT: { 3101 SDValue Sel = Op.getOperand(0); 3102 SDValue LHS = Op.getOperand(1); 3103 SDValue RHS = Op.getOperand(2); 3104 3105 // Try to transform the select condition based on the current demanded 3106 // elements. 3107 APInt UndefSel, UndefZero; 3108 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, UndefZero, TLO, 3109 Depth + 1)) 3110 return true; 3111 3112 // See if we can simplify either vselect operand. 3113 APInt DemandedLHS(DemandedElts); 3114 APInt DemandedRHS(DemandedElts); 3115 APInt UndefLHS, ZeroLHS; 3116 APInt UndefRHS, ZeroRHS; 3117 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3118 Depth + 1)) 3119 return true; 3120 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3121 Depth + 1)) 3122 return true; 3123 3124 KnownUndef = UndefLHS & UndefRHS; 3125 KnownZero = ZeroLHS & ZeroRHS; 3126 3127 // If we know that the selected element is always zero, we don't need the 3128 // select value element. 3129 APInt DemandedSel = DemandedElts & ~KnownZero; 3130 if (DemandedSel != DemandedElts) 3131 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, UndefZero, TLO, 3132 Depth + 1)) 3133 return true; 3134 3135 break; 3136 } 3137 case ISD::VECTOR_SHUFFLE: { 3138 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3139 3140 // Collect demanded elements from shuffle operands.. 3141 APInt DemandedLHS(NumElts, 0); 3142 APInt DemandedRHS(NumElts, 0); 3143 for (unsigned i = 0; i != NumElts; ++i) { 3144 int M = ShuffleMask[i]; 3145 if (M < 0 || !DemandedElts[i]) 3146 continue; 3147 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3148 if (M < (int)NumElts) 3149 DemandedLHS.setBit(M); 3150 else 3151 DemandedRHS.setBit(M - NumElts); 3152 } 3153 3154 // See if we can simplify either shuffle operand. 3155 APInt UndefLHS, ZeroLHS; 3156 APInt UndefRHS, ZeroRHS; 3157 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3158 ZeroLHS, TLO, Depth + 1)) 3159 return true; 3160 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3161 ZeroRHS, TLO, Depth + 1)) 3162 return true; 3163 3164 // Simplify mask using undef elements from LHS/RHS. 3165 bool Updated = false; 3166 bool IdentityLHS = true, IdentityRHS = true; 3167 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3168 for (unsigned i = 0; i != NumElts; ++i) { 3169 int &M = NewMask[i]; 3170 if (M < 0) 3171 continue; 3172 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3173 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3174 Updated = true; 3175 M = -1; 3176 } 3177 IdentityLHS &= (M < 0) || (M == (int)i); 3178 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3179 } 3180 3181 // Update legal shuffle masks based on demanded elements if it won't reduce 3182 // to Identity which can cause premature removal of the shuffle mask. 3183 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3184 SDValue LegalShuffle = 3185 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3186 NewMask, TLO.DAG); 3187 if (LegalShuffle) 3188 return TLO.CombineTo(Op, LegalShuffle); 3189 } 3190 3191 // Propagate undef/zero elements from LHS/RHS. 3192 for (unsigned i = 0; i != NumElts; ++i) { 3193 int M = ShuffleMask[i]; 3194 if (M < 0) { 3195 KnownUndef.setBit(i); 3196 } else if (M < (int)NumElts) { 3197 if (UndefLHS[M]) 3198 KnownUndef.setBit(i); 3199 if (ZeroLHS[M]) 3200 KnownZero.setBit(i); 3201 } else { 3202 if (UndefRHS[M - NumElts]) 3203 KnownUndef.setBit(i); 3204 if (ZeroRHS[M - NumElts]) 3205 KnownZero.setBit(i); 3206 } 3207 } 3208 break; 3209 } 3210 case ISD::ANY_EXTEND_VECTOR_INREG: 3211 case ISD::SIGN_EXTEND_VECTOR_INREG: 3212 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3213 APInt SrcUndef, SrcZero; 3214 SDValue Src = Op.getOperand(0); 3215 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3216 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3217 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3218 Depth + 1)) 3219 return true; 3220 KnownZero = SrcZero.zextOrTrunc(NumElts); 3221 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3222 3223 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3224 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3225 DemandedSrcElts == 1) { 3226 // aext - if we just need the bottom element then we can bitcast. 3227 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3228 } 3229 3230 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3231 // zext(undef) upper bits are guaranteed to be zero. 3232 if (DemandedElts.isSubsetOf(KnownUndef)) 3233 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3234 KnownUndef.clearAllBits(); 3235 3236 // zext - if we just need the bottom element then we can mask: 3237 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3238 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3239 Op->isOnlyUserOf(Src.getNode()) && 3240 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3241 SDLoc DL(Op); 3242 EVT SrcVT = Src.getValueType(); 3243 EVT SrcSVT = SrcVT.getScalarType(); 3244 SmallVector<SDValue> MaskElts; 3245 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3246 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3247 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3248 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3249 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3250 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3251 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3252 } 3253 } 3254 } 3255 break; 3256 } 3257 3258 // TODO: There are more binop opcodes that could be handled here - MIN, 3259 // MAX, saturated math, etc. 3260 case ISD::ADD: { 3261 SDValue Op0 = Op.getOperand(0); 3262 SDValue Op1 = Op.getOperand(1); 3263 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3264 APInt UndefLHS, ZeroLHS; 3265 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3266 Depth + 1, /*AssumeSingleUse*/ true)) 3267 return true; 3268 } 3269 LLVM_FALLTHROUGH; 3270 } 3271 case ISD::OR: 3272 case ISD::XOR: 3273 case ISD::SUB: 3274 case ISD::FADD: 3275 case ISD::FSUB: 3276 case ISD::FMUL: 3277 case ISD::FDIV: 3278 case ISD::FREM: { 3279 SDValue Op0 = Op.getOperand(0); 3280 SDValue Op1 = Op.getOperand(1); 3281 3282 APInt UndefRHS, ZeroRHS; 3283 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3284 Depth + 1)) 3285 return true; 3286 APInt UndefLHS, ZeroLHS; 3287 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3288 Depth + 1)) 3289 return true; 3290 3291 KnownZero = ZeroLHS & ZeroRHS; 3292 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3293 3294 // Attempt to avoid multi-use ops if we don't need anything from them. 3295 // TODO - use KnownUndef to relax the demandedelts? 3296 if (!DemandedElts.isAllOnes()) 3297 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3298 return true; 3299 break; 3300 } 3301 case ISD::SHL: 3302 case ISD::SRL: 3303 case ISD::SRA: 3304 case ISD::ROTL: 3305 case ISD::ROTR: { 3306 SDValue Op0 = Op.getOperand(0); 3307 SDValue Op1 = Op.getOperand(1); 3308 3309 APInt UndefRHS, ZeroRHS; 3310 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3311 Depth + 1)) 3312 return true; 3313 APInt UndefLHS, ZeroLHS; 3314 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3315 Depth + 1)) 3316 return true; 3317 3318 KnownZero = ZeroLHS; 3319 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3320 3321 // Attempt to avoid multi-use ops if we don't need anything from them. 3322 // TODO - use KnownUndef to relax the demandedelts? 3323 if (!DemandedElts.isAllOnes()) 3324 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3325 return true; 3326 break; 3327 } 3328 case ISD::MUL: 3329 case ISD::AND: { 3330 SDValue Op0 = Op.getOperand(0); 3331 SDValue Op1 = Op.getOperand(1); 3332 3333 APInt SrcUndef, SrcZero; 3334 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3335 Depth + 1)) 3336 return true; 3337 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3338 TLO, Depth + 1)) 3339 return true; 3340 3341 // If either side has a zero element, then the result element is zero, even 3342 // if the other is an UNDEF. 3343 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3344 // and then handle 'and' nodes with the rest of the binop opcodes. 3345 KnownZero |= SrcZero; 3346 KnownUndef &= SrcUndef; 3347 KnownUndef &= ~KnownZero; 3348 3349 // Attempt to avoid multi-use ops if we don't need anything from them. 3350 // TODO - use KnownUndef to relax the demandedelts? 3351 if (!DemandedElts.isAllOnes()) 3352 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3353 return true; 3354 break; 3355 } 3356 case ISD::TRUNCATE: 3357 case ISD::SIGN_EXTEND: 3358 case ISD::ZERO_EXTEND: 3359 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3360 KnownZero, TLO, Depth + 1)) 3361 return true; 3362 3363 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3364 // zext(undef) upper bits are guaranteed to be zero. 3365 if (DemandedElts.isSubsetOf(KnownUndef)) 3366 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3367 KnownUndef.clearAllBits(); 3368 } 3369 break; 3370 default: { 3371 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3372 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3373 KnownZero, TLO, Depth)) 3374 return true; 3375 } else { 3376 KnownBits Known; 3377 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3378 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3379 TLO, Depth, AssumeSingleUse)) 3380 return true; 3381 } 3382 break; 3383 } 3384 } 3385 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3386 3387 // Constant fold all undef cases. 3388 // TODO: Handle zero cases as well. 3389 if (DemandedElts.isSubsetOf(KnownUndef)) 3390 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3391 3392 return false; 3393 } 3394 3395 /// Determine which of the bits specified in Mask are known to be either zero or 3396 /// one and return them in the Known. 3397 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3398 KnownBits &Known, 3399 const APInt &DemandedElts, 3400 const SelectionDAG &DAG, 3401 unsigned Depth) const { 3402 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3403 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3404 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3405 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3406 "Should use MaskedValueIsZero if you don't know whether Op" 3407 " is a target node!"); 3408 Known.resetAll(); 3409 } 3410 3411 void TargetLowering::computeKnownBitsForTargetInstr( 3412 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3413 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3414 unsigned Depth) const { 3415 Known.resetAll(); 3416 } 3417 3418 void TargetLowering::computeKnownBitsForFrameIndex( 3419 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3420 // The low bits are known zero if the pointer is aligned. 3421 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3422 } 3423 3424 Align TargetLowering::computeKnownAlignForTargetInstr( 3425 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3426 unsigned Depth) const { 3427 return Align(1); 3428 } 3429 3430 /// This method can be implemented by targets that want to expose additional 3431 /// information about sign bits to the DAG Combiner. 3432 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3433 const APInt &, 3434 const SelectionDAG &, 3435 unsigned Depth) const { 3436 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3437 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3438 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3439 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3440 "Should use ComputeNumSignBits if you don't know whether Op" 3441 " is a target node!"); 3442 return 1; 3443 } 3444 3445 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3446 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3447 const MachineRegisterInfo &MRI, unsigned Depth) const { 3448 return 1; 3449 } 3450 3451 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3452 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3453 TargetLoweringOpt &TLO, unsigned Depth) const { 3454 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3455 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3456 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3457 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3458 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3459 " is a target node!"); 3460 return false; 3461 } 3462 3463 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3464 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3465 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3466 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3467 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3468 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3469 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3470 "Should use SimplifyDemandedBits if you don't know whether Op" 3471 " is a target node!"); 3472 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3473 return false; 3474 } 3475 3476 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3477 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3478 SelectionDAG &DAG, unsigned Depth) const { 3479 assert( 3480 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3481 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3482 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3483 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3484 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3485 " is a target node!"); 3486 return SDValue(); 3487 } 3488 3489 SDValue 3490 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3491 SDValue N1, MutableArrayRef<int> Mask, 3492 SelectionDAG &DAG) const { 3493 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3494 if (!LegalMask) { 3495 std::swap(N0, N1); 3496 ShuffleVectorSDNode::commuteMask(Mask); 3497 LegalMask = isShuffleMaskLegal(Mask, VT); 3498 } 3499 3500 if (!LegalMask) 3501 return SDValue(); 3502 3503 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3504 } 3505 3506 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3507 return nullptr; 3508 } 3509 3510 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3511 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3512 bool PoisonOnly, unsigned Depth) const { 3513 assert( 3514 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3515 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3516 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3517 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3518 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3519 " is a target node!"); 3520 return false; 3521 } 3522 3523 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3524 const SelectionDAG &DAG, 3525 bool SNaN, 3526 unsigned Depth) const { 3527 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3528 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3529 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3530 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3531 "Should use isKnownNeverNaN if you don't know whether Op" 3532 " is a target node!"); 3533 return false; 3534 } 3535 3536 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3537 const APInt &DemandedElts, 3538 APInt &UndefElts, 3539 unsigned Depth) const { 3540 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3541 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3542 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3543 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3544 "Should use isSplatValue if you don't know whether Op" 3545 " is a target node!"); 3546 return false; 3547 } 3548 3549 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3550 // work with truncating build vectors and vectors with elements of less than 3551 // 8 bits. 3552 bool TargetLowering::isConstTrueVal(SDValue N) const { 3553 if (!N) 3554 return false; 3555 3556 unsigned EltWidth; 3557 APInt CVal; 3558 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3559 /*AllowTruncation=*/true)) { 3560 CVal = CN->getAPIntValue(); 3561 EltWidth = N.getValueType().getScalarSizeInBits(); 3562 } else 3563 return false; 3564 3565 // If this is a truncating splat, truncate the splat value. 3566 // Otherwise, we may fail to match the expected values below. 3567 if (EltWidth < CVal.getBitWidth()) 3568 CVal = CVal.trunc(EltWidth); 3569 3570 switch (getBooleanContents(N.getValueType())) { 3571 case UndefinedBooleanContent: 3572 return CVal[0]; 3573 case ZeroOrOneBooleanContent: 3574 return CVal.isOne(); 3575 case ZeroOrNegativeOneBooleanContent: 3576 return CVal.isAllOnes(); 3577 } 3578 3579 llvm_unreachable("Invalid boolean contents"); 3580 } 3581 3582 bool TargetLowering::isConstFalseVal(SDValue N) const { 3583 if (!N) 3584 return false; 3585 3586 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3587 if (!CN) { 3588 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3589 if (!BV) 3590 return false; 3591 3592 // Only interested in constant splats, we don't care about undef 3593 // elements in identifying boolean constants and getConstantSplatNode 3594 // returns NULL if all ops are undef; 3595 CN = BV->getConstantSplatNode(); 3596 if (!CN) 3597 return false; 3598 } 3599 3600 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3601 return !CN->getAPIntValue()[0]; 3602 3603 return CN->isZero(); 3604 } 3605 3606 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3607 bool SExt) const { 3608 if (VT == MVT::i1) 3609 return N->isOne(); 3610 3611 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3612 switch (Cnt) { 3613 case TargetLowering::ZeroOrOneBooleanContent: 3614 // An extended value of 1 is always true, unless its original type is i1, 3615 // in which case it will be sign extended to -1. 3616 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3617 case TargetLowering::UndefinedBooleanContent: 3618 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3619 return N->isAllOnes() && SExt; 3620 } 3621 llvm_unreachable("Unexpected enumeration."); 3622 } 3623 3624 /// This helper function of SimplifySetCC tries to optimize the comparison when 3625 /// either operand of the SetCC node is a bitwise-and instruction. 3626 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3627 ISD::CondCode Cond, const SDLoc &DL, 3628 DAGCombinerInfo &DCI) const { 3629 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3630 std::swap(N0, N1); 3631 3632 SelectionDAG &DAG = DCI.DAG; 3633 EVT OpVT = N0.getValueType(); 3634 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3635 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3636 return SDValue(); 3637 3638 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3639 // iff everything but LSB is known zero: 3640 if (Cond == ISD::SETNE && isNullConstant(N1) && 3641 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3642 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3643 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3644 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3645 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3646 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3647 } 3648 3649 // Match these patterns in any of their permutations: 3650 // (X & Y) == Y 3651 // (X & Y) != Y 3652 SDValue X, Y; 3653 if (N0.getOperand(0) == N1) { 3654 X = N0.getOperand(1); 3655 Y = N0.getOperand(0); 3656 } else if (N0.getOperand(1) == N1) { 3657 X = N0.getOperand(0); 3658 Y = N0.getOperand(1); 3659 } else { 3660 return SDValue(); 3661 } 3662 3663 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3664 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3665 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3666 // Note that where Y is variable and is known to have at most one bit set 3667 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3668 // equivalent when Y == 0. 3669 assert(OpVT.isInteger()); 3670 Cond = ISD::getSetCCInverse(Cond, OpVT); 3671 if (DCI.isBeforeLegalizeOps() || 3672 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3673 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3674 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3675 // If the target supports an 'and-not' or 'and-complement' logic operation, 3676 // try to use that to make a comparison operation more efficient. 3677 // But don't do this transform if the mask is a single bit because there are 3678 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3679 // 'rlwinm' on PPC). 3680 3681 // Bail out if the compare operand that we want to turn into a zero is 3682 // already a zero (otherwise, infinite loop). 3683 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3684 if (YConst && YConst->isZero()) 3685 return SDValue(); 3686 3687 // Transform this into: ~X & Y == 0. 3688 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3689 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3690 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3691 } 3692 3693 return SDValue(); 3694 } 3695 3696 /// There are multiple IR patterns that could be checking whether certain 3697 /// truncation of a signed number would be lossy or not. The pattern which is 3698 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3699 /// We are looking for the following pattern: (KeptBits is a constant) 3700 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3701 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3702 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3703 /// We will unfold it into the natural trunc+sext pattern: 3704 /// ((%x << C) a>> C) dstcond %x 3705 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3706 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3707 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3708 const SDLoc &DL) const { 3709 // We must be comparing with a constant. 3710 ConstantSDNode *C1; 3711 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3712 return SDValue(); 3713 3714 // N0 should be: add %x, (1 << (KeptBits-1)) 3715 if (N0->getOpcode() != ISD::ADD) 3716 return SDValue(); 3717 3718 // And we must be 'add'ing a constant. 3719 ConstantSDNode *C01; 3720 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3721 return SDValue(); 3722 3723 SDValue X = N0->getOperand(0); 3724 EVT XVT = X.getValueType(); 3725 3726 // Validate constants ... 3727 3728 APInt I1 = C1->getAPIntValue(); 3729 3730 ISD::CondCode NewCond; 3731 if (Cond == ISD::CondCode::SETULT) { 3732 NewCond = ISD::CondCode::SETEQ; 3733 } else if (Cond == ISD::CondCode::SETULE) { 3734 NewCond = ISD::CondCode::SETEQ; 3735 // But need to 'canonicalize' the constant. 3736 I1 += 1; 3737 } else if (Cond == ISD::CondCode::SETUGT) { 3738 NewCond = ISD::CondCode::SETNE; 3739 // But need to 'canonicalize' the constant. 3740 I1 += 1; 3741 } else if (Cond == ISD::CondCode::SETUGE) { 3742 NewCond = ISD::CondCode::SETNE; 3743 } else 3744 return SDValue(); 3745 3746 APInt I01 = C01->getAPIntValue(); 3747 3748 auto checkConstants = [&I1, &I01]() -> bool { 3749 // Both of them must be power-of-two, and the constant from setcc is bigger. 3750 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3751 }; 3752 3753 if (checkConstants()) { 3754 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3755 } else { 3756 // What if we invert constants? (and the target predicate) 3757 I1.negate(); 3758 I01.negate(); 3759 assert(XVT.isInteger()); 3760 NewCond = getSetCCInverse(NewCond, XVT); 3761 if (!checkConstants()) 3762 return SDValue(); 3763 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3764 } 3765 3766 // They are power-of-two, so which bit is set? 3767 const unsigned KeptBits = I1.logBase2(); 3768 const unsigned KeptBitsMinusOne = I01.logBase2(); 3769 3770 // Magic! 3771 if (KeptBits != (KeptBitsMinusOne + 1)) 3772 return SDValue(); 3773 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3774 3775 // We don't want to do this in every single case. 3776 SelectionDAG &DAG = DCI.DAG; 3777 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3778 XVT, KeptBits)) 3779 return SDValue(); 3780 3781 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3782 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3783 3784 // Unfold into: ((%x << C) a>> C) cond %x 3785 // Where 'cond' will be either 'eq' or 'ne'. 3786 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3787 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3788 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3789 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3790 3791 return T2; 3792 } 3793 3794 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3795 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3796 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3797 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3798 assert(isConstOrConstSplat(N1C) && 3799 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3800 "Should be a comparison with 0."); 3801 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3802 "Valid only for [in]equality comparisons."); 3803 3804 unsigned NewShiftOpcode; 3805 SDValue X, C, Y; 3806 3807 SelectionDAG &DAG = DCI.DAG; 3808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3809 3810 // Look for '(C l>>/<< Y)'. 3811 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3812 // The shift should be one-use. 3813 if (!V.hasOneUse()) 3814 return false; 3815 unsigned OldShiftOpcode = V.getOpcode(); 3816 switch (OldShiftOpcode) { 3817 case ISD::SHL: 3818 NewShiftOpcode = ISD::SRL; 3819 break; 3820 case ISD::SRL: 3821 NewShiftOpcode = ISD::SHL; 3822 break; 3823 default: 3824 return false; // must be a logical shift. 3825 } 3826 // We should be shifting a constant. 3827 // FIXME: best to use isConstantOrConstantVector(). 3828 C = V.getOperand(0); 3829 ConstantSDNode *CC = 3830 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3831 if (!CC) 3832 return false; 3833 Y = V.getOperand(1); 3834 3835 ConstantSDNode *XC = 3836 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3837 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3838 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3839 }; 3840 3841 // LHS of comparison should be an one-use 'and'. 3842 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3843 return SDValue(); 3844 3845 X = N0.getOperand(0); 3846 SDValue Mask = N0.getOperand(1); 3847 3848 // 'and' is commutative! 3849 if (!Match(Mask)) { 3850 std::swap(X, Mask); 3851 if (!Match(Mask)) 3852 return SDValue(); 3853 } 3854 3855 EVT VT = X.getValueType(); 3856 3857 // Produce: 3858 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3859 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3860 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3861 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3862 return T2; 3863 } 3864 3865 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3866 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3867 /// handle the commuted versions of these patterns. 3868 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3869 ISD::CondCode Cond, const SDLoc &DL, 3870 DAGCombinerInfo &DCI) const { 3871 unsigned BOpcode = N0.getOpcode(); 3872 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3873 "Unexpected binop"); 3874 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3875 3876 // (X + Y) == X --> Y == 0 3877 // (X - Y) == X --> Y == 0 3878 // (X ^ Y) == X --> Y == 0 3879 SelectionDAG &DAG = DCI.DAG; 3880 EVT OpVT = N0.getValueType(); 3881 SDValue X = N0.getOperand(0); 3882 SDValue Y = N0.getOperand(1); 3883 if (X == N1) 3884 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3885 3886 if (Y != N1) 3887 return SDValue(); 3888 3889 // (X + Y) == Y --> X == 0 3890 // (X ^ Y) == Y --> X == 0 3891 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3892 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3893 3894 // The shift would not be valid if the operands are boolean (i1). 3895 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3896 return SDValue(); 3897 3898 // (X - Y) == Y --> X == Y << 1 3899 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3900 !DCI.isBeforeLegalize()); 3901 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3902 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3903 if (!DCI.isCalledByLegalizer()) 3904 DCI.AddToWorklist(YShl1.getNode()); 3905 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3906 } 3907 3908 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3909 SDValue N0, const APInt &C1, 3910 ISD::CondCode Cond, const SDLoc &dl, 3911 SelectionDAG &DAG) { 3912 // Look through truncs that don't change the value of a ctpop. 3913 // FIXME: Add vector support? Need to be careful with setcc result type below. 3914 SDValue CTPOP = N0; 3915 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3916 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3917 CTPOP = N0.getOperand(0); 3918 3919 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3920 return SDValue(); 3921 3922 EVT CTVT = CTPOP.getValueType(); 3923 SDValue CTOp = CTPOP.getOperand(0); 3924 3925 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3926 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3927 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3928 return SDValue(); 3929 3930 // (ctpop x) u< 2 -> (x & x-1) == 0 3931 // (ctpop x) u> 1 -> (x & x-1) != 0 3932 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3933 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3934 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3935 return SDValue(); 3936 if (C1 == 0 && (Cond == ISD::SETULT)) 3937 return SDValue(); // This is handled elsewhere. 3938 3939 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3940 3941 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3942 SDValue Result = CTOp; 3943 for (unsigned i = 0; i < Passes; i++) { 3944 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3945 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3946 } 3947 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3948 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3949 } 3950 3951 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3952 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3953 // For scalars, keep CTPOP if it is legal or custom. 3954 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3955 return SDValue(); 3956 // This is based on X86's custom lowering for CTPOP which produces more 3957 // instructions than the expansion here. 3958 3959 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3960 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3961 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3962 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3963 assert(CTVT.isInteger()); 3964 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3965 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3966 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3967 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3968 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3969 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3970 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3971 } 3972 3973 return SDValue(); 3974 } 3975 3976 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3977 ISD::CondCode Cond, const SDLoc &dl, 3978 SelectionDAG &DAG) { 3979 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3980 return SDValue(); 3981 3982 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3983 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3984 return SDValue(); 3985 3986 auto getRotateSource = [](SDValue X) { 3987 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3988 return X.getOperand(0); 3989 return SDValue(); 3990 }; 3991 3992 // Peek through a rotated value compared against 0 or -1: 3993 // (rot X, Y) == 0/-1 --> X == 0/-1 3994 // (rot X, Y) != 0/-1 --> X != 0/-1 3995 if (SDValue R = getRotateSource(N0)) 3996 return DAG.getSetCC(dl, VT, R, N1, Cond); 3997 3998 // Peek through an 'or' of a rotated value compared against 0: 3999 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 4000 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 4001 // 4002 // TODO: Add the 'and' with -1 sibling. 4003 // TODO: Recurse through a series of 'or' ops to find the rotate. 4004 EVT OpVT = N0.getValueType(); 4005 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 4006 if (SDValue R = getRotateSource(N0.getOperand(0))) { 4007 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 4008 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4009 } 4010 if (SDValue R = getRotateSource(N0.getOperand(1))) { 4011 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 4012 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4013 } 4014 } 4015 4016 return SDValue(); 4017 } 4018 4019 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 4020 ISD::CondCode Cond, const SDLoc &dl, 4021 SelectionDAG &DAG) { 4022 // If we are testing for all-bits-clear, we might be able to do that with 4023 // less shifting since bit-order does not matter. 4024 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4025 return SDValue(); 4026 4027 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4028 if (!C1 || !C1->isZero()) 4029 return SDValue(); 4030 4031 if (!N0.hasOneUse() || 4032 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4033 return SDValue(); 4034 4035 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4036 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4037 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4038 return SDValue(); 4039 4040 // Canonicalize fshr as fshl to reduce pattern-matching. 4041 unsigned ShAmt = ShAmtC->getZExtValue(); 4042 if (N0.getOpcode() == ISD::FSHR) 4043 ShAmt = BitWidth - ShAmt; 4044 4045 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4046 SDValue X, Y; 4047 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4048 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4049 return false; 4050 if (Or.getOperand(0) == Other) { 4051 X = Or.getOperand(0); 4052 Y = Or.getOperand(1); 4053 return true; 4054 } 4055 if (Or.getOperand(1) == Other) { 4056 X = Or.getOperand(1); 4057 Y = Or.getOperand(0); 4058 return true; 4059 } 4060 return false; 4061 }; 4062 4063 EVT OpVT = N0.getValueType(); 4064 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4065 SDValue F0 = N0.getOperand(0); 4066 SDValue F1 = N0.getOperand(1); 4067 if (matchOr(F0, F1)) { 4068 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4069 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4070 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4071 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4072 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4073 } 4074 if (matchOr(F1, F0)) { 4075 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4076 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4077 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4078 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4079 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4080 } 4081 4082 return SDValue(); 4083 } 4084 4085 /// Try to simplify a setcc built with the specified operands and cc. If it is 4086 /// unable to simplify it, return a null SDValue. 4087 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4088 ISD::CondCode Cond, bool foldBooleans, 4089 DAGCombinerInfo &DCI, 4090 const SDLoc &dl) const { 4091 SelectionDAG &DAG = DCI.DAG; 4092 const DataLayout &Layout = DAG.getDataLayout(); 4093 EVT OpVT = N0.getValueType(); 4094 4095 // Constant fold or commute setcc. 4096 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4097 return Fold; 4098 4099 bool N0ConstOrSplat = 4100 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4101 bool N1ConstOrSplat = 4102 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4103 4104 // Ensure that the constant occurs on the RHS and fold constant comparisons. 4105 // TODO: Handle non-splat vector constants. All undef causes trouble. 4106 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4107 // infinite loop here when we encounter one. 4108 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4109 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4110 (DCI.isBeforeLegalizeOps() || 4111 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4112 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4113 4114 // If we have a subtract with the same 2 non-constant operands as this setcc 4115 // -- but in reverse order -- then try to commute the operands of this setcc 4116 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4117 // instruction on some targets. 4118 if (!N0ConstOrSplat && !N1ConstOrSplat && 4119 (DCI.isBeforeLegalizeOps() || 4120 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4121 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4122 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4123 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4124 4125 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4126 return V; 4127 4128 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4129 return V; 4130 4131 if (auto *N1C = isConstOrConstSplat(N1)) { 4132 const APInt &C1 = N1C->getAPIntValue(); 4133 4134 // Optimize some CTPOP cases. 4135 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4136 return V; 4137 4138 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4139 // equality comparison, then we're just comparing whether X itself is 4140 // zero. 4141 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4142 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4143 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4144 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4145 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4146 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4147 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4148 // (srl (ctlz x), 5) == 0 -> X != 0 4149 // (srl (ctlz x), 5) != 1 -> X != 0 4150 Cond = ISD::SETNE; 4151 } else { 4152 // (srl (ctlz x), 5) != 0 -> X == 0 4153 // (srl (ctlz x), 5) == 1 -> X == 0 4154 Cond = ISD::SETEQ; 4155 } 4156 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4157 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4158 Cond); 4159 } 4160 } 4161 } 4162 } 4163 4164 // FIXME: Support vectors. 4165 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4166 const APInt &C1 = N1C->getAPIntValue(); 4167 4168 // (zext x) == C --> x == (trunc C) 4169 // (sext x) == C --> x == (trunc C) 4170 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4171 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4172 unsigned MinBits = N0.getValueSizeInBits(); 4173 SDValue PreExt; 4174 bool Signed = false; 4175 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4176 // ZExt 4177 MinBits = N0->getOperand(0).getValueSizeInBits(); 4178 PreExt = N0->getOperand(0); 4179 } else if (N0->getOpcode() == ISD::AND) { 4180 // DAGCombine turns costly ZExts into ANDs 4181 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4182 if ((C->getAPIntValue()+1).isPowerOf2()) { 4183 MinBits = C->getAPIntValue().countTrailingOnes(); 4184 PreExt = N0->getOperand(0); 4185 } 4186 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4187 // SExt 4188 MinBits = N0->getOperand(0).getValueSizeInBits(); 4189 PreExt = N0->getOperand(0); 4190 Signed = true; 4191 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4192 // ZEXTLOAD / SEXTLOAD 4193 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4194 MinBits = LN0->getMemoryVT().getSizeInBits(); 4195 PreExt = N0; 4196 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4197 Signed = true; 4198 MinBits = LN0->getMemoryVT().getSizeInBits(); 4199 PreExt = N0; 4200 } 4201 } 4202 4203 // Figure out how many bits we need to preserve this constant. 4204 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4205 4206 // Make sure we're not losing bits from the constant. 4207 if (MinBits > 0 && 4208 MinBits < C1.getBitWidth() && 4209 MinBits >= ReqdBits) { 4210 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4211 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4212 // Will get folded away. 4213 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4214 if (MinBits == 1 && C1 == 1) 4215 // Invert the condition. 4216 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4217 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4218 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4219 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4220 } 4221 4222 // If truncating the setcc operands is not desirable, we can still 4223 // simplify the expression in some cases: 4224 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4225 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4226 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4227 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4228 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4229 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4230 SDValue TopSetCC = N0->getOperand(0); 4231 unsigned N0Opc = N0->getOpcode(); 4232 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4233 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4234 TopSetCC.getOpcode() == ISD::SETCC && 4235 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4236 (isConstFalseVal(N1) || 4237 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4238 4239 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4240 (!N1C->isZero() && Cond == ISD::SETNE); 4241 4242 if (!Inverse) 4243 return TopSetCC; 4244 4245 ISD::CondCode InvCond = ISD::getSetCCInverse( 4246 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4247 TopSetCC.getOperand(0).getValueType()); 4248 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4249 TopSetCC.getOperand(1), 4250 InvCond); 4251 } 4252 } 4253 } 4254 4255 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4256 // equality or unsigned, and all 1 bits of the const are in the same 4257 // partial word, see if we can shorten the load. 4258 if (DCI.isBeforeLegalize() && 4259 !ISD::isSignedIntSetCC(Cond) && 4260 N0.getOpcode() == ISD::AND && C1 == 0 && 4261 N0.getNode()->hasOneUse() && 4262 isa<LoadSDNode>(N0.getOperand(0)) && 4263 N0.getOperand(0).getNode()->hasOneUse() && 4264 isa<ConstantSDNode>(N0.getOperand(1))) { 4265 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4266 APInt bestMask; 4267 unsigned bestWidth = 0, bestOffset = 0; 4268 if (Lod->isSimple() && Lod->isUnindexed()) { 4269 unsigned origWidth = N0.getValueSizeInBits(); 4270 unsigned maskWidth = origWidth; 4271 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4272 // 8 bits, but have to be careful... 4273 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4274 origWidth = Lod->getMemoryVT().getSizeInBits(); 4275 const APInt &Mask = N0.getConstantOperandAPInt(1); 4276 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4277 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4278 for (unsigned offset=0; offset<origWidth/width; offset++) { 4279 if (Mask.isSubsetOf(newMask)) { 4280 if (Layout.isLittleEndian()) 4281 bestOffset = (uint64_t)offset * (width/8); 4282 else 4283 bestOffset = (origWidth/width - offset - 1) * (width/8); 4284 bestMask = Mask.lshr(offset * (width/8) * 8); 4285 bestWidth = width; 4286 break; 4287 } 4288 newMask <<= width; 4289 } 4290 } 4291 } 4292 if (bestWidth) { 4293 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4294 if (newVT.isRound() && 4295 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4296 SDValue Ptr = Lod->getBasePtr(); 4297 if (bestOffset != 0) 4298 Ptr = 4299 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4300 SDValue NewLoad = 4301 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4302 Lod->getPointerInfo().getWithOffset(bestOffset), 4303 Lod->getOriginalAlign()); 4304 return DAG.getSetCC(dl, VT, 4305 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4306 DAG.getConstant(bestMask.trunc(bestWidth), 4307 dl, newVT)), 4308 DAG.getConstant(0LL, dl, newVT), Cond); 4309 } 4310 } 4311 } 4312 4313 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4314 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4315 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4316 4317 // If the comparison constant has bits in the upper part, the 4318 // zero-extended value could never match. 4319 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4320 C1.getBitWidth() - InSize))) { 4321 switch (Cond) { 4322 case ISD::SETUGT: 4323 case ISD::SETUGE: 4324 case ISD::SETEQ: 4325 return DAG.getConstant(0, dl, VT); 4326 case ISD::SETULT: 4327 case ISD::SETULE: 4328 case ISD::SETNE: 4329 return DAG.getConstant(1, dl, VT); 4330 case ISD::SETGT: 4331 case ISD::SETGE: 4332 // True if the sign bit of C1 is set. 4333 return DAG.getConstant(C1.isNegative(), dl, VT); 4334 case ISD::SETLT: 4335 case ISD::SETLE: 4336 // True if the sign bit of C1 isn't set. 4337 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4338 default: 4339 break; 4340 } 4341 } 4342 4343 // Otherwise, we can perform the comparison with the low bits. 4344 switch (Cond) { 4345 case ISD::SETEQ: 4346 case ISD::SETNE: 4347 case ISD::SETUGT: 4348 case ISD::SETUGE: 4349 case ISD::SETULT: 4350 case ISD::SETULE: { 4351 EVT newVT = N0.getOperand(0).getValueType(); 4352 if (DCI.isBeforeLegalizeOps() || 4353 (isOperationLegal(ISD::SETCC, newVT) && 4354 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4355 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4356 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4357 4358 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4359 NewConst, Cond); 4360 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4361 } 4362 break; 4363 } 4364 default: 4365 break; // todo, be more careful with signed comparisons 4366 } 4367 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4368 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4369 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4370 OpVT)) { 4371 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4372 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4373 EVT ExtDstTy = N0.getValueType(); 4374 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4375 4376 // If the constant doesn't fit into the number of bits for the source of 4377 // the sign extension, it is impossible for both sides to be equal. 4378 if (C1.getMinSignedBits() > ExtSrcTyBits) 4379 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4380 4381 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4382 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4383 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4384 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4385 DAG.getConstant(Imm, dl, ExtDstTy)); 4386 if (!DCI.isCalledByLegalizer()) 4387 DCI.AddToWorklist(ZextOp.getNode()); 4388 // Otherwise, make this a use of a zext. 4389 return DAG.getSetCC(dl, VT, ZextOp, 4390 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4391 } else if ((N1C->isZero() || N1C->isOne()) && 4392 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4393 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4394 if (N0.getOpcode() == ISD::SETCC && 4395 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4396 (N0.getValueType() == MVT::i1 || 4397 getBooleanContents(N0.getOperand(0).getValueType()) == 4398 ZeroOrOneBooleanContent)) { 4399 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4400 if (TrueWhenTrue) 4401 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4402 // Invert the condition. 4403 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4404 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4405 if (DCI.isBeforeLegalizeOps() || 4406 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4407 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4408 } 4409 4410 if ((N0.getOpcode() == ISD::XOR || 4411 (N0.getOpcode() == ISD::AND && 4412 N0.getOperand(0).getOpcode() == ISD::XOR && 4413 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4414 isOneConstant(N0.getOperand(1))) { 4415 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4416 // can only do this if the top bits are known zero. 4417 unsigned BitWidth = N0.getValueSizeInBits(); 4418 if (DAG.MaskedValueIsZero(N0, 4419 APInt::getHighBitsSet(BitWidth, 4420 BitWidth-1))) { 4421 // Okay, get the un-inverted input value. 4422 SDValue Val; 4423 if (N0.getOpcode() == ISD::XOR) { 4424 Val = N0.getOperand(0); 4425 } else { 4426 assert(N0.getOpcode() == ISD::AND && 4427 N0.getOperand(0).getOpcode() == ISD::XOR); 4428 // ((X^1)&1)^1 -> X & 1 4429 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4430 N0.getOperand(0).getOperand(0), 4431 N0.getOperand(1)); 4432 } 4433 4434 return DAG.getSetCC(dl, VT, Val, N1, 4435 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4436 } 4437 } else if (N1C->isOne()) { 4438 SDValue Op0 = N0; 4439 if (Op0.getOpcode() == ISD::TRUNCATE) 4440 Op0 = Op0.getOperand(0); 4441 4442 if ((Op0.getOpcode() == ISD::XOR) && 4443 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4444 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4445 SDValue XorLHS = Op0.getOperand(0); 4446 SDValue XorRHS = Op0.getOperand(1); 4447 // Ensure that the input setccs return an i1 type or 0/1 value. 4448 if (Op0.getValueType() == MVT::i1 || 4449 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4450 ZeroOrOneBooleanContent && 4451 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4452 ZeroOrOneBooleanContent)) { 4453 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4454 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4455 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4456 } 4457 } 4458 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4459 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4460 if (Op0.getValueType().bitsGT(VT)) 4461 Op0 = DAG.getNode(ISD::AND, dl, VT, 4462 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4463 DAG.getConstant(1, dl, VT)); 4464 else if (Op0.getValueType().bitsLT(VT)) 4465 Op0 = DAG.getNode(ISD::AND, dl, VT, 4466 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4467 DAG.getConstant(1, dl, VT)); 4468 4469 return DAG.getSetCC(dl, VT, Op0, 4470 DAG.getConstant(0, dl, Op0.getValueType()), 4471 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4472 } 4473 if (Op0.getOpcode() == ISD::AssertZext && 4474 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4475 return DAG.getSetCC(dl, VT, Op0, 4476 DAG.getConstant(0, dl, Op0.getValueType()), 4477 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4478 } 4479 } 4480 4481 // Given: 4482 // icmp eq/ne (urem %x, %y), 0 4483 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4484 // icmp eq/ne %x, 0 4485 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4486 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4487 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4488 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4489 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4490 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4491 } 4492 4493 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4494 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4495 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4496 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4497 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4498 N1C && N1C->isAllOnes()) { 4499 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4500 DAG.getConstant(0, dl, OpVT), 4501 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4502 } 4503 4504 if (SDValue V = 4505 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4506 return V; 4507 } 4508 4509 // These simplifications apply to splat vectors as well. 4510 // TODO: Handle more splat vector cases. 4511 if (auto *N1C = isConstOrConstSplat(N1)) { 4512 const APInt &C1 = N1C->getAPIntValue(); 4513 4514 APInt MinVal, MaxVal; 4515 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4516 if (ISD::isSignedIntSetCC(Cond)) { 4517 MinVal = APInt::getSignedMinValue(OperandBitSize); 4518 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4519 } else { 4520 MinVal = APInt::getMinValue(OperandBitSize); 4521 MaxVal = APInt::getMaxValue(OperandBitSize); 4522 } 4523 4524 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4525 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4526 // X >= MIN --> true 4527 if (C1 == MinVal) 4528 return DAG.getBoolConstant(true, dl, VT, OpVT); 4529 4530 if (!VT.isVector()) { // TODO: Support this for vectors. 4531 // X >= C0 --> X > (C0 - 1) 4532 APInt C = C1 - 1; 4533 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4534 if ((DCI.isBeforeLegalizeOps() || 4535 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4536 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4537 isLegalICmpImmediate(C.getSExtValue())))) { 4538 return DAG.getSetCC(dl, VT, N0, 4539 DAG.getConstant(C, dl, N1.getValueType()), 4540 NewCC); 4541 } 4542 } 4543 } 4544 4545 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4546 // X <= MAX --> true 4547 if (C1 == MaxVal) 4548 return DAG.getBoolConstant(true, dl, VT, OpVT); 4549 4550 // X <= C0 --> X < (C0 + 1) 4551 if (!VT.isVector()) { // TODO: Support this for vectors. 4552 APInt C = C1 + 1; 4553 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4554 if ((DCI.isBeforeLegalizeOps() || 4555 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4556 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4557 isLegalICmpImmediate(C.getSExtValue())))) { 4558 return DAG.getSetCC(dl, VT, N0, 4559 DAG.getConstant(C, dl, N1.getValueType()), 4560 NewCC); 4561 } 4562 } 4563 } 4564 4565 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4566 if (C1 == MinVal) 4567 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4568 4569 // TODO: Support this for vectors after legalize ops. 4570 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4571 // Canonicalize setlt X, Max --> setne X, Max 4572 if (C1 == MaxVal) 4573 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4574 4575 // If we have setult X, 1, turn it into seteq X, 0 4576 if (C1 == MinVal+1) 4577 return DAG.getSetCC(dl, VT, N0, 4578 DAG.getConstant(MinVal, dl, N0.getValueType()), 4579 ISD::SETEQ); 4580 } 4581 } 4582 4583 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4584 if (C1 == MaxVal) 4585 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4586 4587 // TODO: Support this for vectors after legalize ops. 4588 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4589 // Canonicalize setgt X, Min --> setne X, Min 4590 if (C1 == MinVal) 4591 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4592 4593 // If we have setugt X, Max-1, turn it into seteq X, Max 4594 if (C1 == MaxVal-1) 4595 return DAG.getSetCC(dl, VT, N0, 4596 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4597 ISD::SETEQ); 4598 } 4599 } 4600 4601 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4602 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4603 if (C1.isZero()) 4604 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4605 VT, N0, N1, Cond, DCI, dl)) 4606 return CC; 4607 4608 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4609 // For example, when high 32-bits of i64 X are known clear: 4610 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4611 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4612 bool CmpZero = N1C->getAPIntValue().isZero(); 4613 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4614 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4615 // Match or(lo,shl(hi,bw/2)) pattern. 4616 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4617 unsigned EltBits = V.getScalarValueSizeInBits(); 4618 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4619 return false; 4620 SDValue LHS = V.getOperand(0); 4621 SDValue RHS = V.getOperand(1); 4622 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4623 // Unshifted element must have zero upperbits. 4624 if (RHS.getOpcode() == ISD::SHL && 4625 isa<ConstantSDNode>(RHS.getOperand(1)) && 4626 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4627 DAG.MaskedValueIsZero(LHS, HiBits)) { 4628 Lo = LHS; 4629 Hi = RHS.getOperand(0); 4630 return true; 4631 } 4632 if (LHS.getOpcode() == ISD::SHL && 4633 isa<ConstantSDNode>(LHS.getOperand(1)) && 4634 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4635 DAG.MaskedValueIsZero(RHS, HiBits)) { 4636 Lo = RHS; 4637 Hi = LHS.getOperand(0); 4638 return true; 4639 } 4640 return false; 4641 }; 4642 4643 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4644 unsigned EltBits = N0.getScalarValueSizeInBits(); 4645 unsigned HalfBits = EltBits / 2; 4646 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4647 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4648 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4649 SDValue NewN0 = 4650 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4651 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4652 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4653 }; 4654 4655 SDValue Lo, Hi; 4656 if (IsConcat(N0, Lo, Hi)) 4657 return MergeConcat(Lo, Hi); 4658 4659 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4660 SDValue Lo0, Lo1, Hi0, Hi1; 4661 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4662 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4663 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4664 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4665 } 4666 } 4667 } 4668 } 4669 4670 // If we have "setcc X, C0", check to see if we can shrink the immediate 4671 // by changing cc. 4672 // TODO: Support this for vectors after legalize ops. 4673 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4674 // SETUGT X, SINTMAX -> SETLT X, 0 4675 // SETUGE X, SINTMIN -> SETLT X, 0 4676 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4677 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4678 return DAG.getSetCC(dl, VT, N0, 4679 DAG.getConstant(0, dl, N1.getValueType()), 4680 ISD::SETLT); 4681 4682 // SETULT X, SINTMIN -> SETGT X, -1 4683 // SETULE X, SINTMAX -> SETGT X, -1 4684 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4685 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4686 return DAG.getSetCC(dl, VT, N0, 4687 DAG.getAllOnesConstant(dl, N1.getValueType()), 4688 ISD::SETGT); 4689 } 4690 } 4691 4692 // Back to non-vector simplifications. 4693 // TODO: Can we do these for vector splats? 4694 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4696 const APInt &C1 = N1C->getAPIntValue(); 4697 EVT ShValTy = N0.getValueType(); 4698 4699 // Fold bit comparisons when we can. This will result in an 4700 // incorrect value when boolean false is negative one, unless 4701 // the bitsize is 1 in which case the false value is the same 4702 // in practice regardless of the representation. 4703 if ((VT.getSizeInBits() == 1 || 4704 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4705 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4706 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4707 N0.getOpcode() == ISD::AND) { 4708 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4709 EVT ShiftTy = 4710 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4711 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4712 // Perform the xform if the AND RHS is a single bit. 4713 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4714 if (AndRHS->getAPIntValue().isPowerOf2() && 4715 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4716 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4717 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4718 DAG.getConstant(ShCt, dl, ShiftTy))); 4719 } 4720 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4721 // (X & 8) == 8 --> (X & 8) >> 3 4722 // Perform the xform if C1 is a single bit. 4723 unsigned ShCt = C1.logBase2(); 4724 if (C1.isPowerOf2() && 4725 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4726 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4727 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4728 DAG.getConstant(ShCt, dl, ShiftTy))); 4729 } 4730 } 4731 } 4732 } 4733 4734 if (C1.getMinSignedBits() <= 64 && 4735 !isLegalICmpImmediate(C1.getSExtValue())) { 4736 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4737 // (X & -256) == 256 -> (X >> 8) == 1 4738 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4739 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4740 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4741 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4742 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4743 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4744 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4745 SDValue Shift = 4746 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4747 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4748 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4749 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4750 } 4751 } 4752 } 4753 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4754 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4755 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4756 // X < 0x100000000 -> (X >> 32) < 1 4757 // X >= 0x100000000 -> (X >> 32) >= 1 4758 // X <= 0x0ffffffff -> (X >> 32) < 1 4759 // X > 0x0ffffffff -> (X >> 32) >= 1 4760 unsigned ShiftBits; 4761 APInt NewC = C1; 4762 ISD::CondCode NewCond = Cond; 4763 if (AdjOne) { 4764 ShiftBits = C1.countTrailingOnes(); 4765 NewC = NewC + 1; 4766 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4767 } else { 4768 ShiftBits = C1.countTrailingZeros(); 4769 } 4770 NewC.lshrInPlace(ShiftBits); 4771 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4772 isLegalICmpImmediate(NewC.getSExtValue()) && 4773 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4774 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4775 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4776 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4777 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4778 } 4779 } 4780 } 4781 } 4782 4783 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4784 auto *CFP = cast<ConstantFPSDNode>(N1); 4785 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4786 4787 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4788 // constant if knowing that the operand is non-nan is enough. We prefer to 4789 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4790 // materialize 0.0. 4791 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4792 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4793 4794 // setcc (fneg x), C -> setcc swap(pred) x, -C 4795 if (N0.getOpcode() == ISD::FNEG) { 4796 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4797 if (DCI.isBeforeLegalizeOps() || 4798 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4799 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4800 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4801 } 4802 } 4803 4804 // If the condition is not legal, see if we can find an equivalent one 4805 // which is legal. 4806 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4807 // If the comparison was an awkward floating-point == or != and one of 4808 // the comparison operands is infinity or negative infinity, convert the 4809 // condition to a less-awkward <= or >=. 4810 if (CFP->getValueAPF().isInfinity()) { 4811 bool IsNegInf = CFP->getValueAPF().isNegative(); 4812 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4813 switch (Cond) { 4814 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4815 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4816 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4817 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4818 default: break; 4819 } 4820 if (NewCond != ISD::SETCC_INVALID && 4821 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4822 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4823 } 4824 } 4825 } 4826 4827 if (N0 == N1) { 4828 // The sext(setcc()) => setcc() optimization relies on the appropriate 4829 // constant being emitted. 4830 assert(!N0.getValueType().isInteger() && 4831 "Integer types should be handled by FoldSetCC"); 4832 4833 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4834 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4835 if (UOF == 2) // FP operators that are undefined on NaNs. 4836 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4837 if (UOF == unsigned(EqTrue)) 4838 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4839 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4840 // if it is not already. 4841 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4842 if (NewCond != Cond && 4843 (DCI.isBeforeLegalizeOps() || 4844 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4845 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4846 } 4847 4848 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4849 N0.getValueType().isInteger()) { 4850 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4851 N0.getOpcode() == ISD::XOR) { 4852 // Simplify (X+Y) == (X+Z) --> Y == Z 4853 if (N0.getOpcode() == N1.getOpcode()) { 4854 if (N0.getOperand(0) == N1.getOperand(0)) 4855 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4856 if (N0.getOperand(1) == N1.getOperand(1)) 4857 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4858 if (isCommutativeBinOp(N0.getOpcode())) { 4859 // If X op Y == Y op X, try other combinations. 4860 if (N0.getOperand(0) == N1.getOperand(1)) 4861 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4862 Cond); 4863 if (N0.getOperand(1) == N1.getOperand(0)) 4864 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4865 Cond); 4866 } 4867 } 4868 4869 // If RHS is a legal immediate value for a compare instruction, we need 4870 // to be careful about increasing register pressure needlessly. 4871 bool LegalRHSImm = false; 4872 4873 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4874 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4875 // Turn (X+C1) == C2 --> X == C2-C1 4876 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4877 return DAG.getSetCC( 4878 dl, VT, N0.getOperand(0), 4879 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4880 dl, N0.getValueType()), 4881 Cond); 4882 4883 // Turn (X^C1) == C2 --> X == C1^C2 4884 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4885 return DAG.getSetCC( 4886 dl, VT, N0.getOperand(0), 4887 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4888 dl, N0.getValueType()), 4889 Cond); 4890 } 4891 4892 // Turn (C1-X) == C2 --> X == C1-C2 4893 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4894 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4895 return DAG.getSetCC( 4896 dl, VT, N0.getOperand(1), 4897 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4898 dl, N0.getValueType()), 4899 Cond); 4900 4901 // Could RHSC fold directly into a compare? 4902 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4903 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4904 } 4905 4906 // (X+Y) == X --> Y == 0 and similar folds. 4907 // Don't do this if X is an immediate that can fold into a cmp 4908 // instruction and X+Y has other uses. It could be an induction variable 4909 // chain, and the transform would increase register pressure. 4910 if (!LegalRHSImm || N0.hasOneUse()) 4911 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4912 return V; 4913 } 4914 4915 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4916 N1.getOpcode() == ISD::XOR) 4917 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4918 return V; 4919 4920 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4921 return V; 4922 } 4923 4924 // Fold remainder of division by a constant. 4925 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4926 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4927 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4928 4929 // When division is cheap or optimizing for minimum size, 4930 // fall through to DIVREM creation by skipping this fold. 4931 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4932 if (N0.getOpcode() == ISD::UREM) { 4933 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4934 return Folded; 4935 } else if (N0.getOpcode() == ISD::SREM) { 4936 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4937 return Folded; 4938 } 4939 } 4940 } 4941 4942 // Fold away ALL boolean setcc's. 4943 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4944 SDValue Temp; 4945 switch (Cond) { 4946 default: llvm_unreachable("Unknown integer setcc!"); 4947 case ISD::SETEQ: // X == Y -> ~(X^Y) 4948 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4949 N0 = DAG.getNOT(dl, Temp, OpVT); 4950 if (!DCI.isCalledByLegalizer()) 4951 DCI.AddToWorklist(Temp.getNode()); 4952 break; 4953 case ISD::SETNE: // X != Y --> (X^Y) 4954 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4955 break; 4956 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4957 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4958 Temp = DAG.getNOT(dl, N0, OpVT); 4959 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4960 if (!DCI.isCalledByLegalizer()) 4961 DCI.AddToWorklist(Temp.getNode()); 4962 break; 4963 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4964 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4965 Temp = DAG.getNOT(dl, N1, OpVT); 4966 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4967 if (!DCI.isCalledByLegalizer()) 4968 DCI.AddToWorklist(Temp.getNode()); 4969 break; 4970 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4971 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4972 Temp = DAG.getNOT(dl, N0, OpVT); 4973 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4974 if (!DCI.isCalledByLegalizer()) 4975 DCI.AddToWorklist(Temp.getNode()); 4976 break; 4977 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4978 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4979 Temp = DAG.getNOT(dl, N1, OpVT); 4980 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4981 break; 4982 } 4983 if (VT.getScalarType() != MVT::i1) { 4984 if (!DCI.isCalledByLegalizer()) 4985 DCI.AddToWorklist(N0.getNode()); 4986 // FIXME: If running after legalize, we probably can't do this. 4987 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4988 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4989 } 4990 return N0; 4991 } 4992 4993 // Could not fold it. 4994 return SDValue(); 4995 } 4996 4997 /// Returns true (and the GlobalValue and the offset) if the node is a 4998 /// GlobalAddress + offset. 4999 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 5000 int64_t &Offset) const { 5001 5002 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 5003 5004 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 5005 GA = GASD->getGlobal(); 5006 Offset += GASD->getOffset(); 5007 return true; 5008 } 5009 5010 if (N->getOpcode() == ISD::ADD) { 5011 SDValue N1 = N->getOperand(0); 5012 SDValue N2 = N->getOperand(1); 5013 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 5014 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 5015 Offset += V->getSExtValue(); 5016 return true; 5017 } 5018 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 5019 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 5020 Offset += V->getSExtValue(); 5021 return true; 5022 } 5023 } 5024 } 5025 5026 return false; 5027 } 5028 5029 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5030 DAGCombinerInfo &DCI) const { 5031 // Default implementation: no optimization. 5032 return SDValue(); 5033 } 5034 5035 //===----------------------------------------------------------------------===// 5036 // Inline Assembler Implementation Methods 5037 //===----------------------------------------------------------------------===// 5038 5039 TargetLowering::ConstraintType 5040 TargetLowering::getConstraintType(StringRef Constraint) const { 5041 unsigned S = Constraint.size(); 5042 5043 if (S == 1) { 5044 switch (Constraint[0]) { 5045 default: break; 5046 case 'r': 5047 return C_RegisterClass; 5048 case 'm': // memory 5049 case 'o': // offsetable 5050 case 'V': // not offsetable 5051 return C_Memory; 5052 case 'p': // Address. 5053 return C_Address; 5054 case 'n': // Simple Integer 5055 case 'E': // Floating Point Constant 5056 case 'F': // Floating Point Constant 5057 return C_Immediate; 5058 case 'i': // Simple Integer or Relocatable Constant 5059 case 's': // Relocatable Constant 5060 case 'X': // Allow ANY value. 5061 case 'I': // Target registers. 5062 case 'J': 5063 case 'K': 5064 case 'L': 5065 case 'M': 5066 case 'N': 5067 case 'O': 5068 case 'P': 5069 case '<': 5070 case '>': 5071 return C_Other; 5072 } 5073 } 5074 5075 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5076 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5077 return C_Memory; 5078 return C_Register; 5079 } 5080 return C_Unknown; 5081 } 5082 5083 /// Try to replace an X constraint, which matches anything, with another that 5084 /// has more specific requirements based on the type of the corresponding 5085 /// operand. 5086 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5087 if (ConstraintVT.isInteger()) 5088 return "r"; 5089 if (ConstraintVT.isFloatingPoint()) 5090 return "f"; // works for many targets 5091 return nullptr; 5092 } 5093 5094 SDValue TargetLowering::LowerAsmOutputForConstraint( 5095 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 5096 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5097 return SDValue(); 5098 } 5099 5100 /// Lower the specified operand into the Ops vector. 5101 /// If it is invalid, don't add anything to Ops. 5102 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5103 std::string &Constraint, 5104 std::vector<SDValue> &Ops, 5105 SelectionDAG &DAG) const { 5106 5107 if (Constraint.length() > 1) return; 5108 5109 char ConstraintLetter = Constraint[0]; 5110 switch (ConstraintLetter) { 5111 default: break; 5112 case 'X': // Allows any operand 5113 case 'i': // Simple Integer or Relocatable Constant 5114 case 'n': // Simple Integer 5115 case 's': { // Relocatable Constant 5116 5117 ConstantSDNode *C; 5118 uint64_t Offset = 0; 5119 5120 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5121 // etc., since getelementpointer is variadic. We can't use 5122 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5123 // while in this case the GA may be furthest from the root node which is 5124 // likely an ISD::ADD. 5125 while (true) { 5126 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5127 // gcc prints these as sign extended. Sign extend value to 64 bits 5128 // now; without this it would get ZExt'd later in 5129 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5130 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5131 BooleanContent BCont = getBooleanContents(MVT::i64); 5132 ISD::NodeType ExtOpc = 5133 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5134 int64_t ExtVal = 5135 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5136 Ops.push_back( 5137 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5138 return; 5139 } 5140 if (ConstraintLetter != 'n') { 5141 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5142 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5143 GA->getValueType(0), 5144 Offset + GA->getOffset())); 5145 return; 5146 } 5147 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5148 Ops.push_back(DAG.getTargetBlockAddress( 5149 BA->getBlockAddress(), BA->getValueType(0), 5150 Offset + BA->getOffset(), BA->getTargetFlags())); 5151 return; 5152 } 5153 if (isa<BasicBlockSDNode>(Op)) { 5154 Ops.push_back(Op); 5155 return; 5156 } 5157 } 5158 const unsigned OpCode = Op.getOpcode(); 5159 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5160 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5161 Op = Op.getOperand(1); 5162 // Subtraction is not commutative. 5163 else if (OpCode == ISD::ADD && 5164 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5165 Op = Op.getOperand(0); 5166 else 5167 return; 5168 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5169 continue; 5170 } 5171 return; 5172 } 5173 break; 5174 } 5175 } 5176 } 5177 5178 std::pair<unsigned, const TargetRegisterClass *> 5179 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5180 StringRef Constraint, 5181 MVT VT) const { 5182 if (Constraint.empty() || Constraint[0] != '{') 5183 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5184 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5185 5186 // Remove the braces from around the name. 5187 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5188 5189 std::pair<unsigned, const TargetRegisterClass *> R = 5190 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5191 5192 // Figure out which register class contains this reg. 5193 for (const TargetRegisterClass *RC : RI->regclasses()) { 5194 // If none of the value types for this register class are valid, we 5195 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5196 if (!isLegalRC(*RI, *RC)) 5197 continue; 5198 5199 for (const MCPhysReg &PR : *RC) { 5200 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5201 std::pair<unsigned, const TargetRegisterClass *> S = 5202 std::make_pair(PR, RC); 5203 5204 // If this register class has the requested value type, return it, 5205 // otherwise keep searching and return the first class found 5206 // if no other is found which explicitly has the requested type. 5207 if (RI->isTypeLegalForClass(*RC, VT)) 5208 return S; 5209 if (!R.second) 5210 R = S; 5211 } 5212 } 5213 } 5214 5215 return R; 5216 } 5217 5218 //===----------------------------------------------------------------------===// 5219 // Constraint Selection. 5220 5221 /// Return true of this is an input operand that is a matching constraint like 5222 /// "4". 5223 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5224 assert(!ConstraintCode.empty() && "No known constraint!"); 5225 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5226 } 5227 5228 /// If this is an input matching constraint, this method returns the output 5229 /// operand it matches. 5230 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5231 assert(!ConstraintCode.empty() && "No known constraint!"); 5232 return atoi(ConstraintCode.c_str()); 5233 } 5234 5235 /// Split up the constraint string from the inline assembly value into the 5236 /// specific constraints and their prefixes, and also tie in the associated 5237 /// operand values. 5238 /// If this returns an empty vector, and if the constraint string itself 5239 /// isn't empty, there was an error parsing. 5240 TargetLowering::AsmOperandInfoVector 5241 TargetLowering::ParseConstraints(const DataLayout &DL, 5242 const TargetRegisterInfo *TRI, 5243 const CallBase &Call) const { 5244 /// Information about all of the constraints. 5245 AsmOperandInfoVector ConstraintOperands; 5246 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5247 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5248 5249 // Do a prepass over the constraints, canonicalizing them, and building up the 5250 // ConstraintOperands list. 5251 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5252 unsigned ResNo = 0; // ResNo - The result number of the next output. 5253 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number. 5254 5255 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5256 ConstraintOperands.emplace_back(std::move(CI)); 5257 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5258 5259 // Update multiple alternative constraint count. 5260 if (OpInfo.multipleAlternatives.size() > maCount) 5261 maCount = OpInfo.multipleAlternatives.size(); 5262 5263 OpInfo.ConstraintVT = MVT::Other; 5264 5265 // Compute the value type for each operand. 5266 switch (OpInfo.Type) { 5267 case InlineAsm::isOutput: 5268 // Indirect outputs just consume an argument. 5269 if (OpInfo.isIndirect) { 5270 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5271 break; 5272 } 5273 5274 // The return value of the call is this value. As such, there is no 5275 // corresponding argument. 5276 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5277 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5278 OpInfo.ConstraintVT = 5279 getSimpleValueType(DL, STy->getElementType(ResNo)); 5280 } else { 5281 assert(ResNo == 0 && "Asm only has one result!"); 5282 OpInfo.ConstraintVT = 5283 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5284 } 5285 ++ResNo; 5286 break; 5287 case InlineAsm::isInput: 5288 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5289 break; 5290 case InlineAsm::isLabel: 5291 OpInfo.CallOperandVal = 5292 cast<CallBrInst>(&Call)->getBlockAddressForIndirectDest(LabelNo); 5293 OpInfo.ConstraintVT = 5294 getAsmOperandValueType(DL, OpInfo.CallOperandVal->getType()) 5295 .getSimpleVT(); 5296 ++LabelNo; 5297 continue; 5298 case InlineAsm::isClobber: 5299 // Nothing to do. 5300 break; 5301 } 5302 5303 if (OpInfo.CallOperandVal) { 5304 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5305 if (OpInfo.isIndirect) { 5306 OpTy = Call.getParamElementType(ArgNo); 5307 assert(OpTy && "Indirect operand must have elementtype attribute"); 5308 } 5309 5310 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5311 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5312 if (STy->getNumElements() == 1) 5313 OpTy = STy->getElementType(0); 5314 5315 // If OpTy is not a single value, it may be a struct/union that we 5316 // can tile with integers. 5317 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5318 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5319 switch (BitSize) { 5320 default: break; 5321 case 1: 5322 case 8: 5323 case 16: 5324 case 32: 5325 case 64: 5326 case 128: 5327 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5328 break; 5329 } 5330 } 5331 5332 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5333 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5334 ArgNo++; 5335 } 5336 } 5337 5338 // If we have multiple alternative constraints, select the best alternative. 5339 if (!ConstraintOperands.empty()) { 5340 if (maCount) { 5341 unsigned bestMAIndex = 0; 5342 int bestWeight = -1; 5343 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5344 int weight = -1; 5345 unsigned maIndex; 5346 // Compute the sums of the weights for each alternative, keeping track 5347 // of the best (highest weight) one so far. 5348 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5349 int weightSum = 0; 5350 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5351 cIndex != eIndex; ++cIndex) { 5352 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5353 if (OpInfo.Type == InlineAsm::isClobber) 5354 continue; 5355 5356 // If this is an output operand with a matching input operand, 5357 // look up the matching input. If their types mismatch, e.g. one 5358 // is an integer, the other is floating point, or their sizes are 5359 // different, flag it as an maCantMatch. 5360 if (OpInfo.hasMatchingInput()) { 5361 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5362 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5363 if ((OpInfo.ConstraintVT.isInteger() != 5364 Input.ConstraintVT.isInteger()) || 5365 (OpInfo.ConstraintVT.getSizeInBits() != 5366 Input.ConstraintVT.getSizeInBits())) { 5367 weightSum = -1; // Can't match. 5368 break; 5369 } 5370 } 5371 } 5372 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5373 if (weight == -1) { 5374 weightSum = -1; 5375 break; 5376 } 5377 weightSum += weight; 5378 } 5379 // Update best. 5380 if (weightSum > bestWeight) { 5381 bestWeight = weightSum; 5382 bestMAIndex = maIndex; 5383 } 5384 } 5385 5386 // Now select chosen alternative in each constraint. 5387 for (AsmOperandInfo &cInfo : ConstraintOperands) 5388 if (cInfo.Type != InlineAsm::isClobber) 5389 cInfo.selectAlternative(bestMAIndex); 5390 } 5391 } 5392 5393 // Check and hook up tied operands, choose constraint code to use. 5394 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5395 cIndex != eIndex; ++cIndex) { 5396 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5397 5398 // If this is an output operand with a matching input operand, look up the 5399 // matching input. If their types mismatch, e.g. one is an integer, the 5400 // other is floating point, or their sizes are different, flag it as an 5401 // error. 5402 if (OpInfo.hasMatchingInput()) { 5403 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5404 5405 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5406 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5407 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5408 OpInfo.ConstraintVT); 5409 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5410 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5411 Input.ConstraintVT); 5412 if ((OpInfo.ConstraintVT.isInteger() != 5413 Input.ConstraintVT.isInteger()) || 5414 (MatchRC.second != InputRC.second)) { 5415 report_fatal_error("Unsupported asm: input constraint" 5416 " with a matching output constraint of" 5417 " incompatible type!"); 5418 } 5419 } 5420 } 5421 } 5422 5423 return ConstraintOperands; 5424 } 5425 5426 /// Return an integer indicating how general CT is. 5427 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5428 switch (CT) { 5429 case TargetLowering::C_Immediate: 5430 case TargetLowering::C_Other: 5431 case TargetLowering::C_Unknown: 5432 return 0; 5433 case TargetLowering::C_Register: 5434 return 1; 5435 case TargetLowering::C_RegisterClass: 5436 return 2; 5437 case TargetLowering::C_Memory: 5438 case TargetLowering::C_Address: 5439 return 3; 5440 } 5441 llvm_unreachable("Invalid constraint type"); 5442 } 5443 5444 /// Examine constraint type and operand type and determine a weight value. 5445 /// This object must already have been set up with the operand type 5446 /// and the current alternative constraint selected. 5447 TargetLowering::ConstraintWeight 5448 TargetLowering::getMultipleConstraintMatchWeight( 5449 AsmOperandInfo &info, int maIndex) const { 5450 InlineAsm::ConstraintCodeVector *rCodes; 5451 if (maIndex >= (int)info.multipleAlternatives.size()) 5452 rCodes = &info.Codes; 5453 else 5454 rCodes = &info.multipleAlternatives[maIndex].Codes; 5455 ConstraintWeight BestWeight = CW_Invalid; 5456 5457 // Loop over the options, keeping track of the most general one. 5458 for (const std::string &rCode : *rCodes) { 5459 ConstraintWeight weight = 5460 getSingleConstraintMatchWeight(info, rCode.c_str()); 5461 if (weight > BestWeight) 5462 BestWeight = weight; 5463 } 5464 5465 return BestWeight; 5466 } 5467 5468 /// Examine constraint type and operand type and determine a weight value. 5469 /// This object must already have been set up with the operand type 5470 /// and the current alternative constraint selected. 5471 TargetLowering::ConstraintWeight 5472 TargetLowering::getSingleConstraintMatchWeight( 5473 AsmOperandInfo &info, const char *constraint) const { 5474 ConstraintWeight weight = CW_Invalid; 5475 Value *CallOperandVal = info.CallOperandVal; 5476 // If we don't have a value, we can't do a match, 5477 // but allow it at the lowest weight. 5478 if (!CallOperandVal) 5479 return CW_Default; 5480 // Look at the constraint type. 5481 switch (*constraint) { 5482 case 'i': // immediate integer. 5483 case 'n': // immediate integer with a known value. 5484 if (isa<ConstantInt>(CallOperandVal)) 5485 weight = CW_Constant; 5486 break; 5487 case 's': // non-explicit intregal immediate. 5488 if (isa<GlobalValue>(CallOperandVal)) 5489 weight = CW_Constant; 5490 break; 5491 case 'E': // immediate float if host format. 5492 case 'F': // immediate float. 5493 if (isa<ConstantFP>(CallOperandVal)) 5494 weight = CW_Constant; 5495 break; 5496 case '<': // memory operand with autodecrement. 5497 case '>': // memory operand with autoincrement. 5498 case 'm': // memory operand. 5499 case 'o': // offsettable memory operand 5500 case 'V': // non-offsettable memory operand 5501 weight = CW_Memory; 5502 break; 5503 case 'r': // general register. 5504 case 'g': // general register, memory operand or immediate integer. 5505 // note: Clang converts "g" to "imr". 5506 if (CallOperandVal->getType()->isIntegerTy()) 5507 weight = CW_Register; 5508 break; 5509 case 'X': // any operand. 5510 default: 5511 weight = CW_Default; 5512 break; 5513 } 5514 return weight; 5515 } 5516 5517 /// If there are multiple different constraints that we could pick for this 5518 /// operand (e.g. "imr") try to pick the 'best' one. 5519 /// This is somewhat tricky: constraints fall into four classes: 5520 /// Other -> immediates and magic values 5521 /// Register -> one specific register 5522 /// RegisterClass -> a group of regs 5523 /// Memory -> memory 5524 /// Ideally, we would pick the most specific constraint possible: if we have 5525 /// something that fits into a register, we would pick it. The problem here 5526 /// is that if we have something that could either be in a register or in 5527 /// memory that use of the register could cause selection of *other* 5528 /// operands to fail: they might only succeed if we pick memory. Because of 5529 /// this the heuristic we use is: 5530 /// 5531 /// 1) If there is an 'other' constraint, and if the operand is valid for 5532 /// that constraint, use it. This makes us take advantage of 'i' 5533 /// constraints when available. 5534 /// 2) Otherwise, pick the most general constraint present. This prefers 5535 /// 'm' over 'r', for example. 5536 /// 5537 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5538 const TargetLowering &TLI, 5539 SDValue Op, SelectionDAG *DAG) { 5540 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5541 unsigned BestIdx = 0; 5542 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5543 int BestGenerality = -1; 5544 5545 // Loop over the options, keeping track of the most general one. 5546 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5547 TargetLowering::ConstraintType CType = 5548 TLI.getConstraintType(OpInfo.Codes[i]); 5549 5550 // Indirect 'other' or 'immediate' constraints are not allowed. 5551 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5552 CType == TargetLowering::C_Register || 5553 CType == TargetLowering::C_RegisterClass)) 5554 continue; 5555 5556 // If this is an 'other' or 'immediate' constraint, see if the operand is 5557 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5558 // the operand is an integer in the range [0..31] we want to use I (saving a 5559 // load of a register), otherwise we must use 'r'. 5560 if ((CType == TargetLowering::C_Other || 5561 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5562 assert(OpInfo.Codes[i].size() == 1 && 5563 "Unhandled multi-letter 'other' constraint"); 5564 std::vector<SDValue> ResultOps; 5565 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5566 ResultOps, *DAG); 5567 if (!ResultOps.empty()) { 5568 BestType = CType; 5569 BestIdx = i; 5570 break; 5571 } 5572 } 5573 5574 // Things with matching constraints can only be registers, per gcc 5575 // documentation. This mainly affects "g" constraints. 5576 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5577 continue; 5578 5579 // This constraint letter is more general than the previous one, use it. 5580 int Generality = getConstraintGenerality(CType); 5581 if (Generality > BestGenerality) { 5582 BestType = CType; 5583 BestIdx = i; 5584 BestGenerality = Generality; 5585 } 5586 } 5587 5588 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5589 OpInfo.ConstraintType = BestType; 5590 } 5591 5592 /// Determines the constraint code and constraint type to use for the specific 5593 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5594 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5595 SDValue Op, 5596 SelectionDAG *DAG) const { 5597 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5598 5599 // Single-letter constraints ('r') are very common. 5600 if (OpInfo.Codes.size() == 1) { 5601 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5602 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5603 } else { 5604 ChooseConstraint(OpInfo, *this, Op, DAG); 5605 } 5606 5607 // 'X' matches anything. 5608 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5609 // Constants are handled elsewhere. For Functions, the type here is the 5610 // type of the result, which is not what we want to look at; leave them 5611 // alone. 5612 Value *v = OpInfo.CallOperandVal; 5613 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5614 return; 5615 } 5616 5617 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5618 OpInfo.ConstraintCode = "i"; 5619 return; 5620 } 5621 5622 // Otherwise, try to resolve it to something we know about by looking at 5623 // the actual operand type. 5624 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5625 OpInfo.ConstraintCode = Repl; 5626 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5627 } 5628 } 5629 } 5630 5631 /// Given an exact SDIV by a constant, create a multiplication 5632 /// with the multiplicative inverse of the constant. 5633 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5634 const SDLoc &dl, SelectionDAG &DAG, 5635 SmallVectorImpl<SDNode *> &Created) { 5636 SDValue Op0 = N->getOperand(0); 5637 SDValue Op1 = N->getOperand(1); 5638 EVT VT = N->getValueType(0); 5639 EVT SVT = VT.getScalarType(); 5640 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5641 EVT ShSVT = ShVT.getScalarType(); 5642 5643 bool UseSRA = false; 5644 SmallVector<SDValue, 16> Shifts, Factors; 5645 5646 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5647 if (C->isZero()) 5648 return false; 5649 APInt Divisor = C->getAPIntValue(); 5650 unsigned Shift = Divisor.countTrailingZeros(); 5651 if (Shift) { 5652 Divisor.ashrInPlace(Shift); 5653 UseSRA = true; 5654 } 5655 // Calculate the multiplicative inverse, using Newton's method. 5656 APInt t; 5657 APInt Factor = Divisor; 5658 while ((t = Divisor * Factor) != 1) 5659 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5660 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5661 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5662 return true; 5663 }; 5664 5665 // Collect all magic values from the build vector. 5666 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5667 return SDValue(); 5668 5669 SDValue Shift, Factor; 5670 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5671 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5672 Factor = DAG.getBuildVector(VT, dl, Factors); 5673 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5674 assert(Shifts.size() == 1 && Factors.size() == 1 && 5675 "Expected matchUnaryPredicate to return one element for scalable " 5676 "vectors"); 5677 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5678 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5679 } else { 5680 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5681 Shift = Shifts[0]; 5682 Factor = Factors[0]; 5683 } 5684 5685 SDValue Res = Op0; 5686 5687 // Shift the value upfront if it is even, so the LSB is one. 5688 if (UseSRA) { 5689 // TODO: For UDIV use SRL instead of SRA. 5690 SDNodeFlags Flags; 5691 Flags.setExact(true); 5692 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5693 Created.push_back(Res.getNode()); 5694 } 5695 5696 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5697 } 5698 5699 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5700 SelectionDAG &DAG, 5701 SmallVectorImpl<SDNode *> &Created) const { 5702 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5704 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5705 return SDValue(N, 0); // Lower SDIV as SDIV 5706 return SDValue(); 5707 } 5708 5709 SDValue 5710 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5711 SelectionDAG &DAG, 5712 SmallVectorImpl<SDNode *> &Created) const { 5713 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5715 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5716 return SDValue(N, 0); // Lower SREM as SREM 5717 return SDValue(); 5718 } 5719 5720 /// Given an ISD::SDIV node expressing a divide by constant, 5721 /// return a DAG expression to select that will generate the same value by 5722 /// multiplying by a magic number. 5723 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5724 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5725 bool IsAfterLegalization, 5726 SmallVectorImpl<SDNode *> &Created) const { 5727 SDLoc dl(N); 5728 EVT VT = N->getValueType(0); 5729 EVT SVT = VT.getScalarType(); 5730 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5731 EVT ShSVT = ShVT.getScalarType(); 5732 unsigned EltBits = VT.getScalarSizeInBits(); 5733 EVT MulVT; 5734 5735 // Check to see if we can do this. 5736 // FIXME: We should be more aggressive here. 5737 if (!isTypeLegal(VT)) { 5738 // Limit this to simple scalars for now. 5739 if (VT.isVector() || !VT.isSimple()) 5740 return SDValue(); 5741 5742 // If this type will be promoted to a large enough type with a legal 5743 // multiply operation, we can go ahead and do this transform. 5744 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5745 return SDValue(); 5746 5747 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5748 if (MulVT.getSizeInBits() < (2 * EltBits) || 5749 !isOperationLegal(ISD::MUL, MulVT)) 5750 return SDValue(); 5751 } 5752 5753 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5754 if (N->getFlags().hasExact()) 5755 return BuildExactSDIV(*this, N, dl, DAG, Created); 5756 5757 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5758 5759 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5760 if (C->isZero()) 5761 return false; 5762 5763 const APInt &Divisor = C->getAPIntValue(); 5764 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5765 int NumeratorFactor = 0; 5766 int ShiftMask = -1; 5767 5768 if (Divisor.isOne() || Divisor.isAllOnes()) { 5769 // If d is +1/-1, we just multiply the numerator by +1/-1. 5770 NumeratorFactor = Divisor.getSExtValue(); 5771 magics.Magic = 0; 5772 magics.ShiftAmount = 0; 5773 ShiftMask = 0; 5774 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5775 // If d > 0 and m < 0, add the numerator. 5776 NumeratorFactor = 1; 5777 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5778 // If d < 0 and m > 0, subtract the numerator. 5779 NumeratorFactor = -1; 5780 } 5781 5782 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5783 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5784 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5785 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5786 return true; 5787 }; 5788 5789 SDValue N0 = N->getOperand(0); 5790 SDValue N1 = N->getOperand(1); 5791 5792 // Collect the shifts / magic values from each element. 5793 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5794 return SDValue(); 5795 5796 SDValue MagicFactor, Factor, Shift, ShiftMask; 5797 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5798 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5799 Factor = DAG.getBuildVector(VT, dl, Factors); 5800 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5801 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5802 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5803 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5804 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5805 "Expected matchUnaryPredicate to return one element for scalable " 5806 "vectors"); 5807 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5808 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5809 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5810 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5811 } else { 5812 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5813 MagicFactor = MagicFactors[0]; 5814 Factor = Factors[0]; 5815 Shift = Shifts[0]; 5816 ShiftMask = ShiftMasks[0]; 5817 } 5818 5819 // Multiply the numerator (operand 0) by the magic value. 5820 // FIXME: We should support doing a MUL in a wider type. 5821 auto GetMULHS = [&](SDValue X, SDValue Y) { 5822 // If the type isn't legal, use a wider mul of the the type calculated 5823 // earlier. 5824 if (!isTypeLegal(VT)) { 5825 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5826 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5827 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5828 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5829 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5830 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5831 } 5832 5833 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5834 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5835 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5836 SDValue LoHi = 5837 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5838 return SDValue(LoHi.getNode(), 1); 5839 } 5840 return SDValue(); 5841 }; 5842 5843 SDValue Q = GetMULHS(N0, MagicFactor); 5844 if (!Q) 5845 return SDValue(); 5846 5847 Created.push_back(Q.getNode()); 5848 5849 // (Optionally) Add/subtract the numerator using Factor. 5850 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5851 Created.push_back(Factor.getNode()); 5852 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5853 Created.push_back(Q.getNode()); 5854 5855 // Shift right algebraic by shift value. 5856 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5857 Created.push_back(Q.getNode()); 5858 5859 // Extract the sign bit, mask it and add it to the quotient. 5860 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5861 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5862 Created.push_back(T.getNode()); 5863 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5864 Created.push_back(T.getNode()); 5865 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5866 } 5867 5868 /// Given an ISD::UDIV node expressing a divide by constant, 5869 /// return a DAG expression to select that will generate the same value by 5870 /// multiplying by a magic number. 5871 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5872 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5873 bool IsAfterLegalization, 5874 SmallVectorImpl<SDNode *> &Created) const { 5875 SDLoc dl(N); 5876 EVT VT = N->getValueType(0); 5877 EVT SVT = VT.getScalarType(); 5878 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5879 EVT ShSVT = ShVT.getScalarType(); 5880 unsigned EltBits = VT.getScalarSizeInBits(); 5881 EVT MulVT; 5882 5883 // Check to see if we can do this. 5884 // FIXME: We should be more aggressive here. 5885 if (!isTypeLegal(VT)) { 5886 // Limit this to simple scalars for now. 5887 if (VT.isVector() || !VT.isSimple()) 5888 return SDValue(); 5889 5890 // If this type will be promoted to a large enough type with a legal 5891 // multiply operation, we can go ahead and do this transform. 5892 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5893 return SDValue(); 5894 5895 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5896 if (MulVT.getSizeInBits() < (2 * EltBits) || 5897 !isOperationLegal(ISD::MUL, MulVT)) 5898 return SDValue(); 5899 } 5900 5901 bool UseNPQ = false; 5902 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5903 5904 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5905 if (C->isZero()) 5906 return false; 5907 // FIXME: We should use a narrower constant when the upper 5908 // bits are known to be zero. 5909 const APInt& Divisor = C->getAPIntValue(); 5910 UnsignedDivisionByConstantInfo magics = 5911 UnsignedDivisionByConstantInfo::get(Divisor); 5912 unsigned PreShift = 0, PostShift = 0; 5913 5914 // If the divisor is even, we can avoid using the expensive fixup by 5915 // shifting the divided value upfront. 5916 if (magics.IsAdd && !Divisor[0]) { 5917 PreShift = Divisor.countTrailingZeros(); 5918 // Get magic number for the shifted divisor. 5919 magics = 5920 UnsignedDivisionByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5921 assert(!magics.IsAdd && "Should use cheap fixup now"); 5922 } 5923 5924 unsigned SelNPQ; 5925 if (!magics.IsAdd || Divisor.isOne()) { 5926 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5927 "We shouldn't generate an undefined shift!"); 5928 PostShift = magics.ShiftAmount; 5929 SelNPQ = false; 5930 } else { 5931 PostShift = magics.ShiftAmount - 1; 5932 SelNPQ = true; 5933 } 5934 5935 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5936 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5937 NPQFactors.push_back( 5938 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5939 : APInt::getZero(EltBits), 5940 dl, SVT)); 5941 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5942 UseNPQ |= SelNPQ; 5943 return true; 5944 }; 5945 5946 SDValue N0 = N->getOperand(0); 5947 SDValue N1 = N->getOperand(1); 5948 5949 // Collect the shifts/magic values from each element. 5950 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5951 return SDValue(); 5952 5953 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5954 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5955 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5956 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5957 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5958 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5959 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5960 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5961 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5962 "Expected matchUnaryPredicate to return one for scalable vectors"); 5963 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5964 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5965 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5966 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5967 } else { 5968 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5969 PreShift = PreShifts[0]; 5970 MagicFactor = MagicFactors[0]; 5971 PostShift = PostShifts[0]; 5972 } 5973 5974 SDValue Q = N0; 5975 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5976 Created.push_back(Q.getNode()); 5977 5978 // FIXME: We should support doing a MUL in a wider type. 5979 auto GetMULHU = [&](SDValue X, SDValue Y) { 5980 // If the type isn't legal, use a wider mul of the the type calculated 5981 // earlier. 5982 if (!isTypeLegal(VT)) { 5983 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5984 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5985 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5986 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5987 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5988 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5989 } 5990 5991 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5992 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5993 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5994 SDValue LoHi = 5995 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5996 return SDValue(LoHi.getNode(), 1); 5997 } 5998 return SDValue(); // No mulhu or equivalent 5999 }; 6000 6001 // Multiply the numerator (operand 0) by the magic value. 6002 Q = GetMULHU(Q, MagicFactor); 6003 if (!Q) 6004 return SDValue(); 6005 6006 Created.push_back(Q.getNode()); 6007 6008 if (UseNPQ) { 6009 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 6010 Created.push_back(NPQ.getNode()); 6011 6012 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 6013 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 6014 if (VT.isVector()) 6015 NPQ = GetMULHU(NPQ, NPQFactor); 6016 else 6017 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 6018 6019 Created.push_back(NPQ.getNode()); 6020 6021 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 6022 Created.push_back(Q.getNode()); 6023 } 6024 6025 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 6026 Created.push_back(Q.getNode()); 6027 6028 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6029 6030 SDValue One = DAG.getConstant(1, dl, VT); 6031 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 6032 return DAG.getSelect(dl, VT, IsOne, N0, Q); 6033 } 6034 6035 /// If all values in Values that *don't* match the predicate are same 'splat' 6036 /// value, then replace all values with that splat value. 6037 /// Else, if AlternativeReplacement was provided, then replace all values that 6038 /// do match predicate with AlternativeReplacement value. 6039 static void 6040 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6041 std::function<bool(SDValue)> Predicate, 6042 SDValue AlternativeReplacement = SDValue()) { 6043 SDValue Replacement; 6044 // Is there a value for which the Predicate does *NOT* match? What is it? 6045 auto SplatValue = llvm::find_if_not(Values, Predicate); 6046 if (SplatValue != Values.end()) { 6047 // Does Values consist only of SplatValue's and values matching Predicate? 6048 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6049 return Value == *SplatValue || Predicate(Value); 6050 })) // Then we shall replace values matching predicate with SplatValue. 6051 Replacement = *SplatValue; 6052 } 6053 if (!Replacement) { 6054 // Oops, we did not find the "baseline" splat value. 6055 if (!AlternativeReplacement) 6056 return; // Nothing to do. 6057 // Let's replace with provided value then. 6058 Replacement = AlternativeReplacement; 6059 } 6060 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6061 } 6062 6063 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6064 /// where the divisor is constant and the comparison target is zero, 6065 /// return a DAG expression that will generate the same comparison result 6066 /// using only multiplications, additions and shifts/rotations. 6067 /// Ref: "Hacker's Delight" 10-17. 6068 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6069 SDValue CompTargetNode, 6070 ISD::CondCode Cond, 6071 DAGCombinerInfo &DCI, 6072 const SDLoc &DL) const { 6073 SmallVector<SDNode *, 5> Built; 6074 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6075 DCI, DL, Built)) { 6076 for (SDNode *N : Built) 6077 DCI.AddToWorklist(N); 6078 return Folded; 6079 } 6080 6081 return SDValue(); 6082 } 6083 6084 SDValue 6085 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6086 SDValue CompTargetNode, ISD::CondCode Cond, 6087 DAGCombinerInfo &DCI, const SDLoc &DL, 6088 SmallVectorImpl<SDNode *> &Created) const { 6089 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6090 // - D must be constant, with D = D0 * 2^K where D0 is odd 6091 // - P is the multiplicative inverse of D0 modulo 2^W 6092 // - Q = floor(((2^W) - 1) / D) 6093 // where W is the width of the common type of N and D. 6094 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6095 "Only applicable for (in)equality comparisons."); 6096 6097 SelectionDAG &DAG = DCI.DAG; 6098 6099 EVT VT = REMNode.getValueType(); 6100 EVT SVT = VT.getScalarType(); 6101 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6102 EVT ShSVT = ShVT.getScalarType(); 6103 6104 // If MUL is unavailable, we cannot proceed in any case. 6105 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6106 return SDValue(); 6107 6108 bool ComparingWithAllZeros = true; 6109 bool AllComparisonsWithNonZerosAreTautological = true; 6110 bool HadTautologicalLanes = false; 6111 bool AllLanesAreTautological = true; 6112 bool HadEvenDivisor = false; 6113 bool AllDivisorsArePowerOfTwo = true; 6114 bool HadTautologicalInvertedLanes = false; 6115 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6116 6117 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6118 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6119 if (CDiv->isZero()) 6120 return false; 6121 6122 const APInt &D = CDiv->getAPIntValue(); 6123 const APInt &Cmp = CCmp->getAPIntValue(); 6124 6125 ComparingWithAllZeros &= Cmp.isZero(); 6126 6127 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6128 // if C2 is not less than C1, the comparison is always false. 6129 // But we will only be able to produce the comparison that will give the 6130 // opposive tautological answer. So this lane would need to be fixed up. 6131 bool TautologicalInvertedLane = D.ule(Cmp); 6132 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6133 6134 // If all lanes are tautological (either all divisors are ones, or divisor 6135 // is not greater than the constant we are comparing with), 6136 // we will prefer to avoid the fold. 6137 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6138 HadTautologicalLanes |= TautologicalLane; 6139 AllLanesAreTautological &= TautologicalLane; 6140 6141 // If we are comparing with non-zero, we need'll need to subtract said 6142 // comparison value from the LHS. But there is no point in doing that if 6143 // every lane where we are comparing with non-zero is tautological.. 6144 if (!Cmp.isZero()) 6145 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6146 6147 // Decompose D into D0 * 2^K 6148 unsigned K = D.countTrailingZeros(); 6149 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6150 APInt D0 = D.lshr(K); 6151 6152 // D is even if it has trailing zeros. 6153 HadEvenDivisor |= (K != 0); 6154 // D is a power-of-two if D0 is one. 6155 // If all divisors are power-of-two, we will prefer to avoid the fold. 6156 AllDivisorsArePowerOfTwo &= D0.isOne(); 6157 6158 // P = inv(D0, 2^W) 6159 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6160 unsigned W = D.getBitWidth(); 6161 APInt P = D0.zext(W + 1) 6162 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6163 .trunc(W); 6164 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6165 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6166 6167 // Q = floor((2^W - 1) u/ D) 6168 // R = ((2^W - 1) u% D) 6169 APInt Q, R; 6170 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6171 6172 // If we are comparing with zero, then that comparison constant is okay, 6173 // else it may need to be one less than that. 6174 if (Cmp.ugt(R)) 6175 Q -= 1; 6176 6177 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6178 "We are expecting that K is always less than all-ones for ShSVT"); 6179 6180 // If the lane is tautological the result can be constant-folded. 6181 if (TautologicalLane) { 6182 // Set P and K amount to a bogus values so we can try to splat them. 6183 P = 0; 6184 K = -1; 6185 // And ensure that comparison constant is tautological, 6186 // it will always compare true/false. 6187 Q = -1; 6188 } 6189 6190 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6191 KAmts.push_back( 6192 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6193 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6194 return true; 6195 }; 6196 6197 SDValue N = REMNode.getOperand(0); 6198 SDValue D = REMNode.getOperand(1); 6199 6200 // Collect the values from each element. 6201 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6202 return SDValue(); 6203 6204 // If all lanes are tautological, the result can be constant-folded. 6205 if (AllLanesAreTautological) 6206 return SDValue(); 6207 6208 // If this is a urem by a powers-of-two, avoid the fold since it can be 6209 // best implemented as a bit test. 6210 if (AllDivisorsArePowerOfTwo) 6211 return SDValue(); 6212 6213 SDValue PVal, KVal, QVal; 6214 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6215 if (HadTautologicalLanes) { 6216 // Try to turn PAmts into a splat, since we don't care about the values 6217 // that are currently '0'. If we can't, just keep '0'`s. 6218 turnVectorIntoSplatVector(PAmts, isNullConstant); 6219 // Try to turn KAmts into a splat, since we don't care about the values 6220 // that are currently '-1'. If we can't, change them to '0'`s. 6221 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6222 DAG.getConstant(0, DL, ShSVT)); 6223 } 6224 6225 PVal = DAG.getBuildVector(VT, DL, PAmts); 6226 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6227 QVal = DAG.getBuildVector(VT, DL, QAmts); 6228 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6229 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6230 "Expected matchBinaryPredicate to return one element for " 6231 "SPLAT_VECTORs"); 6232 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6233 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6234 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6235 } else { 6236 PVal = PAmts[0]; 6237 KVal = KAmts[0]; 6238 QVal = QAmts[0]; 6239 } 6240 6241 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6242 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6243 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6244 assert(CompTargetNode.getValueType() == N.getValueType() && 6245 "Expecting that the types on LHS and RHS of comparisons match."); 6246 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6247 } 6248 6249 // (mul N, P) 6250 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6251 Created.push_back(Op0.getNode()); 6252 6253 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6254 // divisors as a performance improvement, since rotating by 0 is a no-op. 6255 if (HadEvenDivisor) { 6256 // We need ROTR to do this. 6257 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6258 return SDValue(); 6259 // UREM: (rotr (mul N, P), K) 6260 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6261 Created.push_back(Op0.getNode()); 6262 } 6263 6264 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6265 SDValue NewCC = 6266 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6267 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6268 if (!HadTautologicalInvertedLanes) 6269 return NewCC; 6270 6271 // If any lanes previously compared always-false, the NewCC will give 6272 // always-true result for them, so we need to fixup those lanes. 6273 // Or the other way around for inequality predicate. 6274 assert(VT.isVector() && "Can/should only get here for vectors."); 6275 Created.push_back(NewCC.getNode()); 6276 6277 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6278 // if C2 is not less than C1, the comparison is always false. 6279 // But we have produced the comparison that will give the 6280 // opposive tautological answer. So these lanes would need to be fixed up. 6281 SDValue TautologicalInvertedChannels = 6282 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6283 Created.push_back(TautologicalInvertedChannels.getNode()); 6284 6285 // NOTE: we avoid letting illegal types through even if we're before legalize 6286 // ops – legalization has a hard time producing good code for this. 6287 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6288 // If we have a vector select, let's replace the comparison results in the 6289 // affected lanes with the correct tautological result. 6290 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6291 DL, SETCCVT, SETCCVT); 6292 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6293 Replacement, NewCC); 6294 } 6295 6296 // Else, we can just invert the comparison result in the appropriate lanes. 6297 // 6298 // NOTE: see the note above VSELECT above. 6299 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6300 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6301 TautologicalInvertedChannels); 6302 6303 return SDValue(); // Don't know how to lower. 6304 } 6305 6306 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6307 /// where the divisor is constant and the comparison target is zero, 6308 /// return a DAG expression that will generate the same comparison result 6309 /// using only multiplications, additions and shifts/rotations. 6310 /// Ref: "Hacker's Delight" 10-17. 6311 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6312 SDValue CompTargetNode, 6313 ISD::CondCode Cond, 6314 DAGCombinerInfo &DCI, 6315 const SDLoc &DL) const { 6316 SmallVector<SDNode *, 7> Built; 6317 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6318 DCI, DL, Built)) { 6319 assert(Built.size() <= 7 && "Max size prediction failed."); 6320 for (SDNode *N : Built) 6321 DCI.AddToWorklist(N); 6322 return Folded; 6323 } 6324 6325 return SDValue(); 6326 } 6327 6328 SDValue 6329 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6330 SDValue CompTargetNode, ISD::CondCode Cond, 6331 DAGCombinerInfo &DCI, const SDLoc &DL, 6332 SmallVectorImpl<SDNode *> &Created) const { 6333 // Fold: 6334 // (seteq/ne (srem N, D), 0) 6335 // To: 6336 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6337 // 6338 // - D must be constant, with D = D0 * 2^K where D0 is odd 6339 // - P is the multiplicative inverse of D0 modulo 2^W 6340 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6341 // - Q = floor((2 * A) / (2^K)) 6342 // where W is the width of the common type of N and D. 6343 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6344 "Only applicable for (in)equality comparisons."); 6345 6346 SelectionDAG &DAG = DCI.DAG; 6347 6348 EVT VT = REMNode.getValueType(); 6349 EVT SVT = VT.getScalarType(); 6350 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6351 EVT ShSVT = ShVT.getScalarType(); 6352 6353 // If we are after ops legalization, and MUL is unavailable, we can not 6354 // proceed. 6355 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6356 return SDValue(); 6357 6358 // TODO: Could support comparing with non-zero too. 6359 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6360 if (!CompTarget || !CompTarget->isZero()) 6361 return SDValue(); 6362 6363 bool HadIntMinDivisor = false; 6364 bool HadOneDivisor = false; 6365 bool AllDivisorsAreOnes = true; 6366 bool HadEvenDivisor = false; 6367 bool NeedToApplyOffset = false; 6368 bool AllDivisorsArePowerOfTwo = true; 6369 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6370 6371 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6372 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6373 if (C->isZero()) 6374 return false; 6375 6376 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6377 6378 // WARNING: this fold is only valid for positive divisors! 6379 APInt D = C->getAPIntValue(); 6380 if (D.isNegative()) 6381 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6382 6383 HadIntMinDivisor |= D.isMinSignedValue(); 6384 6385 // If all divisors are ones, we will prefer to avoid the fold. 6386 HadOneDivisor |= D.isOne(); 6387 AllDivisorsAreOnes &= D.isOne(); 6388 6389 // Decompose D into D0 * 2^K 6390 unsigned K = D.countTrailingZeros(); 6391 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6392 APInt D0 = D.lshr(K); 6393 6394 if (!D.isMinSignedValue()) { 6395 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6396 // we don't care about this lane in this fold, we'll special-handle it. 6397 HadEvenDivisor |= (K != 0); 6398 } 6399 6400 // D is a power-of-two if D0 is one. This includes INT_MIN. 6401 // If all divisors are power-of-two, we will prefer to avoid the fold. 6402 AllDivisorsArePowerOfTwo &= D0.isOne(); 6403 6404 // P = inv(D0, 2^W) 6405 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6406 unsigned W = D.getBitWidth(); 6407 APInt P = D0.zext(W + 1) 6408 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6409 .trunc(W); 6410 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6411 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6412 6413 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6414 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6415 A.clearLowBits(K); 6416 6417 if (!D.isMinSignedValue()) { 6418 // If divisor INT_MIN, then we don't care about this lane in this fold, 6419 // we'll special-handle it. 6420 NeedToApplyOffset |= A != 0; 6421 } 6422 6423 // Q = floor((2 * A) / (2^K)) 6424 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6425 6426 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6427 "We are expecting that A is always less than all-ones for SVT"); 6428 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6429 "We are expecting that K is always less than all-ones for ShSVT"); 6430 6431 // If the divisor is 1 the result can be constant-folded. Likewise, we 6432 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6433 if (D.isOne()) { 6434 // Set P, A and K to a bogus values so we can try to splat them. 6435 P = 0; 6436 A = -1; 6437 K = -1; 6438 6439 // x ?% 1 == 0 <--> true <--> x u<= -1 6440 Q = -1; 6441 } 6442 6443 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6444 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6445 KAmts.push_back( 6446 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6447 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6448 return true; 6449 }; 6450 6451 SDValue N = REMNode.getOperand(0); 6452 SDValue D = REMNode.getOperand(1); 6453 6454 // Collect the values from each element. 6455 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6456 return SDValue(); 6457 6458 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6459 if (AllDivisorsAreOnes) 6460 return SDValue(); 6461 6462 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6463 // since it can be best implemented as a bit test. 6464 if (AllDivisorsArePowerOfTwo) 6465 return SDValue(); 6466 6467 SDValue PVal, AVal, KVal, QVal; 6468 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6469 if (HadOneDivisor) { 6470 // Try to turn PAmts into a splat, since we don't care about the values 6471 // that are currently '0'. If we can't, just keep '0'`s. 6472 turnVectorIntoSplatVector(PAmts, isNullConstant); 6473 // Try to turn AAmts into a splat, since we don't care about the 6474 // values that are currently '-1'. If we can't, change them to '0'`s. 6475 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6476 DAG.getConstant(0, DL, SVT)); 6477 // Try to turn KAmts into a splat, since we don't care about the values 6478 // that are currently '-1'. If we can't, change them to '0'`s. 6479 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6480 DAG.getConstant(0, DL, ShSVT)); 6481 } 6482 6483 PVal = DAG.getBuildVector(VT, DL, PAmts); 6484 AVal = DAG.getBuildVector(VT, DL, AAmts); 6485 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6486 QVal = DAG.getBuildVector(VT, DL, QAmts); 6487 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6488 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6489 QAmts.size() == 1 && 6490 "Expected matchUnaryPredicate to return one element for scalable " 6491 "vectors"); 6492 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6493 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6494 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6495 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6496 } else { 6497 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6498 PVal = PAmts[0]; 6499 AVal = AAmts[0]; 6500 KVal = KAmts[0]; 6501 QVal = QAmts[0]; 6502 } 6503 6504 // (mul N, P) 6505 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6506 Created.push_back(Op0.getNode()); 6507 6508 if (NeedToApplyOffset) { 6509 // We need ADD to do this. 6510 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6511 return SDValue(); 6512 6513 // (add (mul N, P), A) 6514 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6515 Created.push_back(Op0.getNode()); 6516 } 6517 6518 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6519 // divisors as a performance improvement, since rotating by 0 is a no-op. 6520 if (HadEvenDivisor) { 6521 // We need ROTR to do this. 6522 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6523 return SDValue(); 6524 // SREM: (rotr (add (mul N, P), A), K) 6525 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6526 Created.push_back(Op0.getNode()); 6527 } 6528 6529 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6530 SDValue Fold = 6531 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6532 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6533 6534 // If we didn't have lanes with INT_MIN divisor, then we're done. 6535 if (!HadIntMinDivisor) 6536 return Fold; 6537 6538 // That fold is only valid for positive divisors. Which effectively means, 6539 // it is invalid for INT_MIN divisors. So if we have such a lane, 6540 // we must fix-up results for said lanes. 6541 assert(VT.isVector() && "Can/should only get here for vectors."); 6542 6543 // NOTE: we avoid letting illegal types through even if we're before legalize 6544 // ops – legalization has a hard time producing good code for the code that 6545 // follows. 6546 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6547 !isOperationLegalOrCustom(ISD::AND, VT) || 6548 !isOperationLegalOrCustom(Cond, VT) || 6549 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6550 return SDValue(); 6551 6552 Created.push_back(Fold.getNode()); 6553 6554 SDValue IntMin = DAG.getConstant( 6555 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6556 SDValue IntMax = DAG.getConstant( 6557 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6558 SDValue Zero = 6559 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6560 6561 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6562 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6563 Created.push_back(DivisorIsIntMin.getNode()); 6564 6565 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6566 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6567 Created.push_back(Masked.getNode()); 6568 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6569 Created.push_back(MaskedIsZero.getNode()); 6570 6571 // To produce final result we need to blend 2 vectors: 'SetCC' and 6572 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6573 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6574 // constant-folded, select can get lowered to a shuffle with constant mask. 6575 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6576 MaskedIsZero, Fold); 6577 6578 return Blended; 6579 } 6580 6581 bool TargetLowering:: 6582 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6583 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6584 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6585 "be a constant integer"); 6586 return true; 6587 } 6588 6589 return false; 6590 } 6591 6592 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6593 const DenormalMode &Mode) const { 6594 SDLoc DL(Op); 6595 EVT VT = Op.getValueType(); 6596 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6597 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6598 // Testing it with denormal inputs to avoid wrong estimate. 6599 if (Mode.Input == DenormalMode::IEEE) { 6600 // This is specifically a check for the handling of denormal inputs, 6601 // not the result. 6602 6603 // Test = fabs(X) < SmallestNormal 6604 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6605 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6606 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6607 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6608 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6609 } 6610 // Test = X == 0.0 6611 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6612 } 6613 6614 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6615 bool LegalOps, bool OptForSize, 6616 NegatibleCost &Cost, 6617 unsigned Depth) const { 6618 // fneg is removable even if it has multiple uses. 6619 if (Op.getOpcode() == ISD::FNEG) { 6620 Cost = NegatibleCost::Cheaper; 6621 return Op.getOperand(0); 6622 } 6623 6624 // Don't recurse exponentially. 6625 if (Depth > SelectionDAG::MaxRecursionDepth) 6626 return SDValue(); 6627 6628 // Pre-increment recursion depth for use in recursive calls. 6629 ++Depth; 6630 const SDNodeFlags Flags = Op->getFlags(); 6631 const TargetOptions &Options = DAG.getTarget().Options; 6632 EVT VT = Op.getValueType(); 6633 unsigned Opcode = Op.getOpcode(); 6634 6635 // Don't allow anything with multiple uses unless we know it is free. 6636 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6637 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6638 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6639 if (!IsFreeExtend) 6640 return SDValue(); 6641 } 6642 6643 auto RemoveDeadNode = [&](SDValue N) { 6644 if (N && N.getNode()->use_empty()) 6645 DAG.RemoveDeadNode(N.getNode()); 6646 }; 6647 6648 SDLoc DL(Op); 6649 6650 // Because getNegatedExpression can delete nodes we need a handle to keep 6651 // temporary nodes alive in case the recursion manages to create an identical 6652 // node. 6653 std::list<HandleSDNode> Handles; 6654 6655 switch (Opcode) { 6656 case ISD::ConstantFP: { 6657 // Don't invert constant FP values after legalization unless the target says 6658 // the negated constant is legal. 6659 bool IsOpLegal = 6660 isOperationLegal(ISD::ConstantFP, VT) || 6661 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6662 OptForSize); 6663 6664 if (LegalOps && !IsOpLegal) 6665 break; 6666 6667 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6668 V.changeSign(); 6669 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6670 6671 // If we already have the use of the negated floating constant, it is free 6672 // to negate it even it has multiple uses. 6673 if (!Op.hasOneUse() && CFP.use_empty()) 6674 break; 6675 Cost = NegatibleCost::Neutral; 6676 return CFP; 6677 } 6678 case ISD::BUILD_VECTOR: { 6679 // Only permit BUILD_VECTOR of constants. 6680 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6681 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6682 })) 6683 break; 6684 6685 bool IsOpLegal = 6686 (isOperationLegal(ISD::ConstantFP, VT) && 6687 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6688 llvm::all_of(Op->op_values(), [&](SDValue N) { 6689 return N.isUndef() || 6690 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6691 OptForSize); 6692 }); 6693 6694 if (LegalOps && !IsOpLegal) 6695 break; 6696 6697 SmallVector<SDValue, 4> Ops; 6698 for (SDValue C : Op->op_values()) { 6699 if (C.isUndef()) { 6700 Ops.push_back(C); 6701 continue; 6702 } 6703 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6704 V.changeSign(); 6705 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6706 } 6707 Cost = NegatibleCost::Neutral; 6708 return DAG.getBuildVector(VT, DL, Ops); 6709 } 6710 case ISD::FADD: { 6711 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6712 break; 6713 6714 // After operation legalization, it might not be legal to create new FSUBs. 6715 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6716 break; 6717 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6718 6719 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6720 NegatibleCost CostX = NegatibleCost::Expensive; 6721 SDValue NegX = 6722 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6723 // Prevent this node from being deleted by the next call. 6724 if (NegX) 6725 Handles.emplace_back(NegX); 6726 6727 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6728 NegatibleCost CostY = NegatibleCost::Expensive; 6729 SDValue NegY = 6730 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6731 6732 // We're done with the handles. 6733 Handles.clear(); 6734 6735 // Negate the X if its cost is less or equal than Y. 6736 if (NegX && (CostX <= CostY)) { 6737 Cost = CostX; 6738 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6739 if (NegY != N) 6740 RemoveDeadNode(NegY); 6741 return N; 6742 } 6743 6744 // Negate the Y if it is not expensive. 6745 if (NegY) { 6746 Cost = CostY; 6747 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6748 if (NegX != N) 6749 RemoveDeadNode(NegX); 6750 return N; 6751 } 6752 break; 6753 } 6754 case ISD::FSUB: { 6755 // We can't turn -(A-B) into B-A when we honor signed zeros. 6756 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6757 break; 6758 6759 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6760 // fold (fneg (fsub 0, Y)) -> Y 6761 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6762 if (C->isZero()) { 6763 Cost = NegatibleCost::Cheaper; 6764 return Y; 6765 } 6766 6767 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6768 Cost = NegatibleCost::Neutral; 6769 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6770 } 6771 case ISD::FMUL: 6772 case ISD::FDIV: { 6773 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6774 6775 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6776 NegatibleCost CostX = NegatibleCost::Expensive; 6777 SDValue NegX = 6778 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6779 // Prevent this node from being deleted by the next call. 6780 if (NegX) 6781 Handles.emplace_back(NegX); 6782 6783 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6784 NegatibleCost CostY = NegatibleCost::Expensive; 6785 SDValue NegY = 6786 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6787 6788 // We're done with the handles. 6789 Handles.clear(); 6790 6791 // Negate the X if its cost is less or equal than Y. 6792 if (NegX && (CostX <= CostY)) { 6793 Cost = CostX; 6794 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6795 if (NegY != N) 6796 RemoveDeadNode(NegY); 6797 return N; 6798 } 6799 6800 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6801 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6802 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6803 break; 6804 6805 // Negate the Y if it is not expensive. 6806 if (NegY) { 6807 Cost = CostY; 6808 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6809 if (NegX != N) 6810 RemoveDeadNode(NegX); 6811 return N; 6812 } 6813 break; 6814 } 6815 case ISD::FMA: 6816 case ISD::FMAD: { 6817 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6818 break; 6819 6820 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6821 NegatibleCost CostZ = NegatibleCost::Expensive; 6822 SDValue NegZ = 6823 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6824 // Give up if fail to negate the Z. 6825 if (!NegZ) 6826 break; 6827 6828 // Prevent this node from being deleted by the next two calls. 6829 Handles.emplace_back(NegZ); 6830 6831 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6832 NegatibleCost CostX = NegatibleCost::Expensive; 6833 SDValue NegX = 6834 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6835 // Prevent this node from being deleted by the next call. 6836 if (NegX) 6837 Handles.emplace_back(NegX); 6838 6839 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6840 NegatibleCost CostY = NegatibleCost::Expensive; 6841 SDValue NegY = 6842 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6843 6844 // We're done with the handles. 6845 Handles.clear(); 6846 6847 // Negate the X if its cost is less or equal than Y. 6848 if (NegX && (CostX <= CostY)) { 6849 Cost = std::min(CostX, CostZ); 6850 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6851 if (NegY != N) 6852 RemoveDeadNode(NegY); 6853 return N; 6854 } 6855 6856 // Negate the Y if it is not expensive. 6857 if (NegY) { 6858 Cost = std::min(CostY, CostZ); 6859 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6860 if (NegX != N) 6861 RemoveDeadNode(NegX); 6862 return N; 6863 } 6864 break; 6865 } 6866 6867 case ISD::FP_EXTEND: 6868 case ISD::FSIN: 6869 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6870 OptForSize, Cost, Depth)) 6871 return DAG.getNode(Opcode, DL, VT, NegV); 6872 break; 6873 case ISD::FP_ROUND: 6874 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6875 OptForSize, Cost, Depth)) 6876 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6877 break; 6878 } 6879 6880 return SDValue(); 6881 } 6882 6883 //===----------------------------------------------------------------------===// 6884 // Legalization Utilities 6885 //===----------------------------------------------------------------------===// 6886 6887 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6888 SDValue LHS, SDValue RHS, 6889 SmallVectorImpl<SDValue> &Result, 6890 EVT HiLoVT, SelectionDAG &DAG, 6891 MulExpansionKind Kind, SDValue LL, 6892 SDValue LH, SDValue RL, SDValue RH) const { 6893 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6894 Opcode == ISD::SMUL_LOHI); 6895 6896 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6897 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6898 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6899 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6900 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6901 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6902 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6903 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6904 6905 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6906 return false; 6907 6908 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6909 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6910 6911 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6912 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6913 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6914 6915 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6916 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6917 bool Signed) -> bool { 6918 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6919 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6920 Hi = SDValue(Lo.getNode(), 1); 6921 return true; 6922 } 6923 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6924 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6925 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6926 return true; 6927 } 6928 return false; 6929 }; 6930 6931 SDValue Lo, Hi; 6932 6933 if (!LL.getNode() && !RL.getNode() && 6934 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6935 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6936 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6937 } 6938 6939 if (!LL.getNode()) 6940 return false; 6941 6942 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6943 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6944 DAG.MaskedValueIsZero(RHS, HighMask)) { 6945 // The inputs are both zero-extended. 6946 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6947 Result.push_back(Lo); 6948 Result.push_back(Hi); 6949 if (Opcode != ISD::MUL) { 6950 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6951 Result.push_back(Zero); 6952 Result.push_back(Zero); 6953 } 6954 return true; 6955 } 6956 } 6957 6958 if (!VT.isVector() && Opcode == ISD::MUL && 6959 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6960 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6961 // The input values are both sign-extended. 6962 // TODO non-MUL case? 6963 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6964 Result.push_back(Lo); 6965 Result.push_back(Hi); 6966 return true; 6967 } 6968 } 6969 6970 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6971 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6972 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6973 6974 if (!LH.getNode() && !RH.getNode() && 6975 isOperationLegalOrCustom(ISD::SRL, VT) && 6976 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6977 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6978 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6979 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6980 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6981 } 6982 6983 if (!LH.getNode()) 6984 return false; 6985 6986 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6987 return false; 6988 6989 Result.push_back(Lo); 6990 6991 if (Opcode == ISD::MUL) { 6992 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6993 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6994 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6995 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6996 Result.push_back(Hi); 6997 return true; 6998 } 6999 7000 // Compute the full width result. 7001 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 7002 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 7003 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7004 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 7005 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 7006 }; 7007 7008 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7009 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 7010 return false; 7011 7012 // This is effectively the add part of a multiply-add of half-sized operands, 7013 // so it cannot overflow. 7014 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7015 7016 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 7017 return false; 7018 7019 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7020 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7021 7022 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 7023 isOperationLegalOrCustom(ISD::ADDE, VT)); 7024 if (UseGlue) 7025 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 7026 Merge(Lo, Hi)); 7027 else 7028 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 7029 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 7030 7031 SDValue Carry = Next.getValue(1); 7032 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7033 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7034 7035 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7036 return false; 7037 7038 if (UseGlue) 7039 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7040 Carry); 7041 else 7042 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7043 Zero, Carry); 7044 7045 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7046 7047 if (Opcode == ISD::SMUL_LOHI) { 7048 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7049 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7050 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7051 7052 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7053 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7054 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7055 } 7056 7057 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7058 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7059 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7060 return true; 7061 } 7062 7063 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7064 SelectionDAG &DAG, MulExpansionKind Kind, 7065 SDValue LL, SDValue LH, SDValue RL, 7066 SDValue RH) const { 7067 SmallVector<SDValue, 2> Result; 7068 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7069 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7070 DAG, Kind, LL, LH, RL, RH); 7071 if (Ok) { 7072 assert(Result.size() == 2); 7073 Lo = Result[0]; 7074 Hi = Result[1]; 7075 } 7076 return Ok; 7077 } 7078 7079 // Check that (every element of) Z is undef or not an exact multiple of BW. 7080 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7081 return ISD::matchUnaryPredicate( 7082 Z, 7083 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7084 true); 7085 } 7086 7087 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7088 SelectionDAG &DAG) const { 7089 EVT VT = Node->getValueType(0); 7090 7091 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7092 !isOperationLegalOrCustom(ISD::SRL, VT) || 7093 !isOperationLegalOrCustom(ISD::SUB, VT) || 7094 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7095 return SDValue(); 7096 7097 SDValue X = Node->getOperand(0); 7098 SDValue Y = Node->getOperand(1); 7099 SDValue Z = Node->getOperand(2); 7100 7101 unsigned BW = VT.getScalarSizeInBits(); 7102 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7103 SDLoc DL(SDValue(Node, 0)); 7104 7105 EVT ShVT = Z.getValueType(); 7106 7107 // If a funnel shift in the other direction is more supported, use it. 7108 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7109 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7110 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7111 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7112 // fshl X, Y, Z -> fshr X, Y, -Z 7113 // fshr X, Y, Z -> fshl X, Y, -Z 7114 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7115 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7116 } else { 7117 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7118 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7119 SDValue One = DAG.getConstant(1, DL, ShVT); 7120 if (IsFSHL) { 7121 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7122 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7123 } else { 7124 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7125 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7126 } 7127 Z = DAG.getNOT(DL, Z, ShVT); 7128 } 7129 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7130 } 7131 7132 SDValue ShX, ShY; 7133 SDValue ShAmt, InvShAmt; 7134 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7135 // fshl: X << C | Y >> (BW - C) 7136 // fshr: X << (BW - C) | Y >> C 7137 // where C = Z % BW is not zero 7138 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7139 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7140 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7141 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7142 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7143 } else { 7144 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7145 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7146 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7147 if (isPowerOf2_32(BW)) { 7148 // Z % BW -> Z & (BW - 1) 7149 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7150 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7151 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7152 } else { 7153 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7154 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7155 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7156 } 7157 7158 SDValue One = DAG.getConstant(1, DL, ShVT); 7159 if (IsFSHL) { 7160 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7161 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7162 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7163 } else { 7164 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7165 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7166 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7167 } 7168 } 7169 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7170 } 7171 7172 // TODO: Merge with expandFunnelShift. 7173 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7174 SelectionDAG &DAG) const { 7175 EVT VT = Node->getValueType(0); 7176 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7177 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7178 SDValue Op0 = Node->getOperand(0); 7179 SDValue Op1 = Node->getOperand(1); 7180 SDLoc DL(SDValue(Node, 0)); 7181 7182 EVT ShVT = Op1.getValueType(); 7183 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7184 7185 // If a rotate in the other direction is more supported, use it. 7186 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7187 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7188 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7189 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7190 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7191 } 7192 7193 if (!AllowVectorOps && VT.isVector() && 7194 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7195 !isOperationLegalOrCustom(ISD::SRL, VT) || 7196 !isOperationLegalOrCustom(ISD::SUB, VT) || 7197 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7198 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7199 return SDValue(); 7200 7201 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7202 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7203 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7204 SDValue ShVal; 7205 SDValue HsVal; 7206 if (isPowerOf2_32(EltSizeInBits)) { 7207 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7208 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7209 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7210 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7211 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7212 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7213 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7214 } else { 7215 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7216 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7217 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7218 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7219 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7220 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7221 SDValue One = DAG.getConstant(1, DL, ShVT); 7222 HsVal = 7223 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7224 } 7225 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7226 } 7227 7228 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7229 SelectionDAG &DAG) const { 7230 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7231 EVT VT = Node->getValueType(0); 7232 unsigned VTBits = VT.getScalarSizeInBits(); 7233 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7234 7235 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7236 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7237 SDValue ShOpLo = Node->getOperand(0); 7238 SDValue ShOpHi = Node->getOperand(1); 7239 SDValue ShAmt = Node->getOperand(2); 7240 EVT ShAmtVT = ShAmt.getValueType(); 7241 EVT ShAmtCCVT = 7242 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7243 SDLoc dl(Node); 7244 7245 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7246 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7247 // away during isel. 7248 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7249 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7250 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7251 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7252 : DAG.getConstant(0, dl, VT); 7253 7254 SDValue Tmp2, Tmp3; 7255 if (IsSHL) { 7256 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7257 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7258 } else { 7259 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7260 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7261 } 7262 7263 // If the shift amount is larger or equal than the width of a part we don't 7264 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7265 // values for large shift amounts. 7266 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7267 DAG.getConstant(VTBits, dl, ShAmtVT)); 7268 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7269 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7270 7271 if (IsSHL) { 7272 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7273 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7274 } else { 7275 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7276 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7277 } 7278 } 7279 7280 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7281 SelectionDAG &DAG) const { 7282 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7283 SDValue Src = Node->getOperand(OpNo); 7284 EVT SrcVT = Src.getValueType(); 7285 EVT DstVT = Node->getValueType(0); 7286 SDLoc dl(SDValue(Node, 0)); 7287 7288 // FIXME: Only f32 to i64 conversions are supported. 7289 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7290 return false; 7291 7292 if (Node->isStrictFPOpcode()) 7293 // When a NaN is converted to an integer a trap is allowed. We can't 7294 // use this expansion here because it would eliminate that trap. Other 7295 // traps are also allowed and cannot be eliminated. See 7296 // IEEE 754-2008 sec 5.8. 7297 return false; 7298 7299 // Expand f32 -> i64 conversion 7300 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7301 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7302 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7303 EVT IntVT = SrcVT.changeTypeToInteger(); 7304 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7305 7306 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7307 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7308 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7309 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7310 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7311 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7312 7313 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7314 7315 SDValue ExponentBits = DAG.getNode( 7316 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7317 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7318 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7319 7320 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7321 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7322 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7323 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7324 7325 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7326 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7327 DAG.getConstant(0x00800000, dl, IntVT)); 7328 7329 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7330 7331 R = DAG.getSelectCC( 7332 dl, Exponent, ExponentLoBit, 7333 DAG.getNode(ISD::SHL, dl, DstVT, R, 7334 DAG.getZExtOrTrunc( 7335 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7336 dl, IntShVT)), 7337 DAG.getNode(ISD::SRL, dl, DstVT, R, 7338 DAG.getZExtOrTrunc( 7339 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7340 dl, IntShVT)), 7341 ISD::SETGT); 7342 7343 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7344 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7345 7346 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7347 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7348 return true; 7349 } 7350 7351 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7352 SDValue &Chain, 7353 SelectionDAG &DAG) const { 7354 SDLoc dl(SDValue(Node, 0)); 7355 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7356 SDValue Src = Node->getOperand(OpNo); 7357 7358 EVT SrcVT = Src.getValueType(); 7359 EVT DstVT = Node->getValueType(0); 7360 EVT SetCCVT = 7361 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7362 EVT DstSetCCVT = 7363 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7364 7365 // Only expand vector types if we have the appropriate vector bit operations. 7366 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7367 ISD::FP_TO_SINT; 7368 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7369 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7370 return false; 7371 7372 // If the maximum float value is smaller then the signed integer range, 7373 // the destination signmask can't be represented by the float, so we can 7374 // just use FP_TO_SINT directly. 7375 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7376 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7377 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7378 if (APFloat::opOverflow & 7379 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7380 if (Node->isStrictFPOpcode()) { 7381 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7382 { Node->getOperand(0), Src }); 7383 Chain = Result.getValue(1); 7384 } else 7385 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7386 return true; 7387 } 7388 7389 // Don't expand it if there isn't cheap fsub instruction. 7390 if (!isOperationLegalOrCustom( 7391 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7392 return false; 7393 7394 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7395 SDValue Sel; 7396 7397 if (Node->isStrictFPOpcode()) { 7398 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7399 Node->getOperand(0), /*IsSignaling*/ true); 7400 Chain = Sel.getValue(1); 7401 } else { 7402 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7403 } 7404 7405 bool Strict = Node->isStrictFPOpcode() || 7406 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7407 7408 if (Strict) { 7409 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7410 // signmask then offset (the result of which should be fully representable). 7411 // Sel = Src < 0x8000000000000000 7412 // FltOfs = select Sel, 0, 0x8000000000000000 7413 // IntOfs = select Sel, 0, 0x8000000000000000 7414 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7415 7416 // TODO: Should any fast-math-flags be set for the FSUB? 7417 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7418 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7419 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7420 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7421 DAG.getConstant(0, dl, DstVT), 7422 DAG.getConstant(SignMask, dl, DstVT)); 7423 SDValue SInt; 7424 if (Node->isStrictFPOpcode()) { 7425 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7426 { Chain, Src, FltOfs }); 7427 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7428 { Val.getValue(1), Val }); 7429 Chain = SInt.getValue(1); 7430 } else { 7431 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7432 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7433 } 7434 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7435 } else { 7436 // Expand based on maximum range of FP_TO_SINT: 7437 // True = fp_to_sint(Src) 7438 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7439 // Result = select (Src < 0x8000000000000000), True, False 7440 7441 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7442 // TODO: Should any fast-math-flags be set for the FSUB? 7443 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7444 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7445 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7446 DAG.getConstant(SignMask, dl, DstVT)); 7447 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7448 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7449 } 7450 return true; 7451 } 7452 7453 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7454 SDValue &Chain, 7455 SelectionDAG &DAG) const { 7456 // This transform is not correct for converting 0 when rounding mode is set 7457 // to round toward negative infinity which will produce -0.0. So disable under 7458 // strictfp. 7459 if (Node->isStrictFPOpcode()) 7460 return false; 7461 7462 SDValue Src = Node->getOperand(0); 7463 EVT SrcVT = Src.getValueType(); 7464 EVT DstVT = Node->getValueType(0); 7465 7466 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7467 return false; 7468 7469 // Only expand vector types if we have the appropriate vector bit operations. 7470 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7471 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7472 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7473 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7474 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7475 return false; 7476 7477 SDLoc dl(SDValue(Node, 0)); 7478 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7479 7480 // Implementation of unsigned i64 to f64 following the algorithm in 7481 // __floatundidf in compiler_rt. This implementation performs rounding 7482 // correctly in all rounding modes with the exception of converting 0 7483 // when rounding toward negative infinity. In that case the fsub will produce 7484 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7485 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7486 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7487 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7488 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7489 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7490 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7491 7492 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7493 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7494 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7495 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7496 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7497 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7498 SDValue HiSub = 7499 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7500 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7501 return true; 7502 } 7503 7504 SDValue 7505 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7506 SelectionDAG &DAG) const { 7507 unsigned Opcode = Node->getOpcode(); 7508 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7509 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7510 "Wrong opcode"); 7511 7512 if (Node->getFlags().hasNoNaNs()) { 7513 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7514 SDValue Op1 = Node->getOperand(0); 7515 SDValue Op2 = Node->getOperand(1); 7516 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7517 // Copy FMF flags, but always set the no-signed-zeros flag 7518 // as this is implied by the FMINNUM/FMAXNUM semantics. 7519 SDNodeFlags Flags = Node->getFlags(); 7520 Flags.setNoSignedZeros(true); 7521 SelCC->setFlags(Flags); 7522 return SelCC; 7523 } 7524 7525 return SDValue(); 7526 } 7527 7528 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7529 SelectionDAG &DAG) const { 7530 SDLoc dl(Node); 7531 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7532 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7533 EVT VT = Node->getValueType(0); 7534 7535 if (VT.isScalableVector()) 7536 report_fatal_error( 7537 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7538 7539 if (isOperationLegalOrCustom(NewOp, VT)) { 7540 SDValue Quiet0 = Node->getOperand(0); 7541 SDValue Quiet1 = Node->getOperand(1); 7542 7543 if (!Node->getFlags().hasNoNaNs()) { 7544 // Insert canonicalizes if it's possible we need to quiet to get correct 7545 // sNaN behavior. 7546 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7547 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7548 Node->getFlags()); 7549 } 7550 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7551 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7552 Node->getFlags()); 7553 } 7554 } 7555 7556 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7557 } 7558 7559 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7560 // instead if there are no NaNs. 7561 if (Node->getFlags().hasNoNaNs()) { 7562 unsigned IEEE2018Op = 7563 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7564 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7565 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7566 Node->getOperand(1), Node->getFlags()); 7567 } 7568 } 7569 7570 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7571 return SelCC; 7572 7573 return SDValue(); 7574 } 7575 7576 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7577 unsigned Test, SDNodeFlags Flags, 7578 const SDLoc &DL, 7579 SelectionDAG &DAG) const { 7580 EVT OperandVT = Op.getValueType(); 7581 assert(OperandVT.isFloatingPoint()); 7582 7583 // Degenerated cases. 7584 if (Test == 0) 7585 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7586 if ((Test & fcAllFlags) == fcAllFlags) 7587 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7588 7589 // PPC double double is a pair of doubles, of which the higher part determines 7590 // the value class. 7591 if (OperandVT == MVT::ppcf128) { 7592 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7593 DAG.getConstant(1, DL, MVT::i32)); 7594 OperandVT = MVT::f64; 7595 } 7596 7597 // Some checks may be represented as inversion of simpler check, for example 7598 // "inf|normal|subnormal|zero" => !"nan". 7599 bool IsInverted = false; 7600 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7601 IsInverted = true; 7602 Test = InvertedCheck; 7603 } 7604 7605 // Floating-point type properties. 7606 EVT ScalarFloatVT = OperandVT.getScalarType(); 7607 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7608 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7609 bool IsF80 = (ScalarFloatVT == MVT::f80); 7610 7611 // Some checks can be implemented using float comparisons, if floating point 7612 // exceptions are ignored. 7613 if (Flags.hasNoFPExcept() && 7614 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7615 if (Test == fcZero) 7616 return DAG.getSetCC(DL, ResultVT, Op, 7617 DAG.getConstantFP(0.0, DL, OperandVT), 7618 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7619 if (Test == fcNan) 7620 return DAG.getSetCC(DL, ResultVT, Op, Op, 7621 IsInverted ? ISD::SETO : ISD::SETUO); 7622 } 7623 7624 // In the general case use integer operations. 7625 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7626 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7627 if (OperandVT.isVector()) 7628 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7629 OperandVT.getVectorElementCount()); 7630 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7631 7632 // Various masks. 7633 APInt SignBit = APInt::getSignMask(BitSize); 7634 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7635 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7636 const unsigned ExplicitIntBitInF80 = 63; 7637 APInt ExpMask = Inf; 7638 if (IsF80) 7639 ExpMask.clearBit(ExplicitIntBitInF80); 7640 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7641 APInt QNaNBitMask = 7642 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7643 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7644 7645 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7646 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7647 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7648 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7649 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7650 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7651 7652 SDValue Res; 7653 const auto appendResult = [&](SDValue PartialRes) { 7654 if (PartialRes) { 7655 if (Res) 7656 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7657 else 7658 Res = PartialRes; 7659 } 7660 }; 7661 7662 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7663 const auto getIntBitIsSet = [&]() -> SDValue { 7664 if (!IntBitIsSetV) { 7665 APInt IntBitMask(BitSize, 0); 7666 IntBitMask.setBit(ExplicitIntBitInF80); 7667 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7668 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7669 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7670 } 7671 return IntBitIsSetV; 7672 }; 7673 7674 // Split the value into sign bit and absolute value. 7675 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7676 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7677 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7678 7679 // Tests that involve more than one class should be processed first. 7680 SDValue PartialRes; 7681 7682 if (IsF80) 7683 ; // Detect finite numbers of f80 by checking individual classes because 7684 // they have different settings of the explicit integer bit. 7685 else if ((Test & fcFinite) == fcFinite) { 7686 // finite(V) ==> abs(V) < exp_mask 7687 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7688 Test &= ~fcFinite; 7689 } else if ((Test & fcFinite) == fcPosFinite) { 7690 // finite(V) && V > 0 ==> V < exp_mask 7691 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7692 Test &= ~fcPosFinite; 7693 } else if ((Test & fcFinite) == fcNegFinite) { 7694 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7695 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7696 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7697 Test &= ~fcNegFinite; 7698 } 7699 appendResult(PartialRes); 7700 7701 // Check for individual classes. 7702 7703 if (unsigned PartialCheck = Test & fcZero) { 7704 if (PartialCheck == fcPosZero) 7705 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7706 else if (PartialCheck == fcZero) 7707 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7708 else // ISD::fcNegZero 7709 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7710 appendResult(PartialRes); 7711 } 7712 7713 if (unsigned PartialCheck = Test & fcInf) { 7714 if (PartialCheck == fcPosInf) 7715 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7716 else if (PartialCheck == fcInf) 7717 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7718 else { // ISD::fcNegInf 7719 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7720 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7721 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7722 } 7723 appendResult(PartialRes); 7724 } 7725 7726 if (unsigned PartialCheck = Test & fcNan) { 7727 APInt InfWithQnanBit = Inf | QNaNBitMask; 7728 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7729 if (PartialCheck == fcNan) { 7730 // isnan(V) ==> abs(V) > int(inf) 7731 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7732 if (IsF80) { 7733 // Recognize unsupported values as NaNs for compatibility with glibc. 7734 // In them (exp(V)==0) == int_bit. 7735 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7736 SDValue ExpIsZero = 7737 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7738 SDValue IsPseudo = 7739 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7740 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7741 } 7742 } else if (PartialCheck == fcQNan) { 7743 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7744 PartialRes = 7745 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7746 } else { // ISD::fcSNan 7747 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7748 // abs(V) < (unsigned(Inf) | quiet_bit) 7749 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7750 SDValue IsNotQnan = 7751 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7752 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7753 } 7754 appendResult(PartialRes); 7755 } 7756 7757 if (unsigned PartialCheck = Test & fcSubnormal) { 7758 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7759 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7760 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7761 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7762 SDValue VMinusOneV = 7763 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7764 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7765 if (PartialCheck == fcNegSubnormal) 7766 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7767 appendResult(PartialRes); 7768 } 7769 7770 if (unsigned PartialCheck = Test & fcNormal) { 7771 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7772 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7773 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7774 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7775 APInt ExpLimit = ExpMask - ExpLSB; 7776 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7777 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7778 if (PartialCheck == fcNegNormal) 7779 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7780 else if (PartialCheck == fcPosNormal) { 7781 SDValue PosSignV = 7782 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7783 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7784 } 7785 if (IsF80) 7786 PartialRes = 7787 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7788 appendResult(PartialRes); 7789 } 7790 7791 if (!Res) 7792 return DAG.getConstant(IsInverted, DL, ResultVT); 7793 if (IsInverted) 7794 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7795 return Res; 7796 } 7797 7798 // Only expand vector types if we have the appropriate vector bit operations. 7799 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7800 assert(VT.isVector() && "Expected vector type"); 7801 unsigned Len = VT.getScalarSizeInBits(); 7802 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7803 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7804 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7805 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7806 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7807 } 7808 7809 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7810 SDLoc dl(Node); 7811 EVT VT = Node->getValueType(0); 7812 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7813 SDValue Op = Node->getOperand(0); 7814 unsigned Len = VT.getScalarSizeInBits(); 7815 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7816 7817 // TODO: Add support for irregular type lengths. 7818 if (!(Len <= 128 && Len % 8 == 0)) 7819 return SDValue(); 7820 7821 // Only expand vector types if we have the appropriate vector bit operations. 7822 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7823 return SDValue(); 7824 7825 // This is the "best" algorithm from 7826 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7827 SDValue Mask55 = 7828 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7829 SDValue Mask33 = 7830 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7831 SDValue Mask0F = 7832 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7833 7834 // v = v - ((v >> 1) & 0x55555555...) 7835 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7836 DAG.getNode(ISD::AND, dl, VT, 7837 DAG.getNode(ISD::SRL, dl, VT, Op, 7838 DAG.getConstant(1, dl, ShVT)), 7839 Mask55)); 7840 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7841 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7842 DAG.getNode(ISD::AND, dl, VT, 7843 DAG.getNode(ISD::SRL, dl, VT, Op, 7844 DAG.getConstant(2, dl, ShVT)), 7845 Mask33)); 7846 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7847 Op = DAG.getNode(ISD::AND, dl, VT, 7848 DAG.getNode(ISD::ADD, dl, VT, Op, 7849 DAG.getNode(ISD::SRL, dl, VT, Op, 7850 DAG.getConstant(4, dl, ShVT))), 7851 Mask0F); 7852 7853 if (Len <= 8) 7854 return Op; 7855 7856 // Avoid the multiply if we only have 2 bytes to add. 7857 // TODO: Only doing this for scalars because vectors weren't as obviously 7858 // improved. 7859 if (Len == 16 && !VT.isVector()) { 7860 // v = (v + (v >> 8)) & 0x00FF; 7861 return DAG.getNode(ISD::AND, dl, VT, 7862 DAG.getNode(ISD::ADD, dl, VT, Op, 7863 DAG.getNode(ISD::SRL, dl, VT, Op, 7864 DAG.getConstant(8, dl, ShVT))), 7865 DAG.getConstant(0xFF, dl, VT)); 7866 } 7867 7868 // v = (v * 0x01010101...) >> (Len - 8) 7869 SDValue Mask01 = 7870 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7871 return DAG.getNode(ISD::SRL, dl, VT, 7872 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7873 DAG.getConstant(Len - 8, dl, ShVT)); 7874 } 7875 7876 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7877 SDLoc dl(Node); 7878 EVT VT = Node->getValueType(0); 7879 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7880 SDValue Op = Node->getOperand(0); 7881 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7882 7883 // If the non-ZERO_UNDEF version is supported we can use that instead. 7884 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7885 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7886 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7887 7888 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7889 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7890 EVT SetCCVT = 7891 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7892 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7893 SDValue Zero = DAG.getConstant(0, dl, VT); 7894 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7895 return DAG.getSelect(dl, VT, SrcIsZero, 7896 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7897 } 7898 7899 // Only expand vector types if we have the appropriate vector bit operations. 7900 // This includes the operations needed to expand CTPOP if it isn't supported. 7901 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7902 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7903 !canExpandVectorCTPOP(*this, VT)) || 7904 !isOperationLegalOrCustom(ISD::SRL, VT) || 7905 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7906 return SDValue(); 7907 7908 // for now, we do this: 7909 // x = x | (x >> 1); 7910 // x = x | (x >> 2); 7911 // ... 7912 // x = x | (x >>16); 7913 // x = x | (x >>32); // for 64-bit input 7914 // return popcount(~x); 7915 // 7916 // Ref: "Hacker's Delight" by Henry Warren 7917 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 7918 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7919 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7920 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7921 } 7922 Op = DAG.getNOT(dl, Op, VT); 7923 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7924 } 7925 7926 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7927 SDLoc dl(Node); 7928 EVT VT = Node->getValueType(0); 7929 SDValue Op = Node->getOperand(0); 7930 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7931 7932 // If the non-ZERO_UNDEF version is supported we can use that instead. 7933 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7934 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7935 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7936 7937 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7938 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7939 EVT SetCCVT = 7940 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7941 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7942 SDValue Zero = DAG.getConstant(0, dl, VT); 7943 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7944 return DAG.getSelect(dl, VT, SrcIsZero, 7945 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7946 } 7947 7948 // Only expand vector types if we have the appropriate vector bit operations. 7949 // This includes the operations needed to expand CTPOP if it isn't supported. 7950 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7951 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7952 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7953 !canExpandVectorCTPOP(*this, VT)) || 7954 !isOperationLegalOrCustom(ISD::SUB, VT) || 7955 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7956 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7957 return SDValue(); 7958 7959 // for now, we use: { return popcount(~x & (x - 1)); } 7960 // unless the target has ctlz but not ctpop, in which case we use: 7961 // { return 32 - nlz(~x & (x-1)); } 7962 // Ref: "Hacker's Delight" by Henry Warren 7963 SDValue Tmp = DAG.getNode( 7964 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7965 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7966 7967 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7968 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7969 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7970 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7971 } 7972 7973 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7974 } 7975 7976 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7977 bool IsNegative) const { 7978 SDLoc dl(N); 7979 EVT VT = N->getValueType(0); 7980 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7981 SDValue Op = N->getOperand(0); 7982 7983 // abs(x) -> smax(x,sub(0,x)) 7984 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7985 isOperationLegal(ISD::SMAX, VT)) { 7986 SDValue Zero = DAG.getConstant(0, dl, VT); 7987 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7988 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7989 } 7990 7991 // abs(x) -> umin(x,sub(0,x)) 7992 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7993 isOperationLegal(ISD::UMIN, VT)) { 7994 SDValue Zero = DAG.getConstant(0, dl, VT); 7995 Op = DAG.getFreeze(Op); 7996 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7997 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7998 } 7999 8000 // 0 - abs(x) -> smin(x, sub(0,x)) 8001 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 8002 isOperationLegal(ISD::SMIN, VT)) { 8003 Op = DAG.getFreeze(Op); 8004 SDValue Zero = DAG.getConstant(0, dl, VT); 8005 return DAG.getNode(ISD::SMIN, dl, VT, Op, 8006 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8007 } 8008 8009 // Only expand vector types if we have the appropriate vector operations. 8010 if (VT.isVector() && 8011 (!isOperationLegalOrCustom(ISD::SRA, VT) || 8012 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 8013 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 8014 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 8015 return SDValue(); 8016 8017 Op = DAG.getFreeze(Op); 8018 SDValue Shift = 8019 DAG.getNode(ISD::SRA, dl, VT, Op, 8020 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 8021 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 8022 8023 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 8024 if (!IsNegative) 8025 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 8026 8027 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 8028 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 8029 } 8030 8031 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 8032 SDLoc dl(N); 8033 EVT VT = N->getValueType(0); 8034 SDValue Op = N->getOperand(0); 8035 8036 if (!VT.isSimple()) 8037 return SDValue(); 8038 8039 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8040 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 8041 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 8042 default: 8043 return SDValue(); 8044 case MVT::i16: 8045 // Use a rotate by 8. This can be further expanded if necessary. 8046 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8047 case MVT::i32: 8048 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8049 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8050 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8051 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8052 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8053 DAG.getConstant(0xFF0000, dl, VT)); 8054 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 8055 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8056 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8057 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8058 case MVT::i64: 8059 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8060 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8061 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8062 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8063 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8064 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8065 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8066 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8067 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 8068 DAG.getConstant(255ULL<<48, dl, VT)); 8069 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 8070 DAG.getConstant(255ULL<<40, dl, VT)); 8071 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 8072 DAG.getConstant(255ULL<<32, dl, VT)); 8073 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 8074 DAG.getConstant(255ULL<<24, dl, VT)); 8075 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8076 DAG.getConstant(255ULL<<16, dl, VT)); 8077 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 8078 DAG.getConstant(255ULL<<8 , dl, VT)); 8079 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 8080 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 8081 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8082 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8083 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 8084 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8085 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 8086 } 8087 } 8088 8089 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 8090 SDLoc dl(N); 8091 EVT VT = N->getValueType(0); 8092 SDValue Op = N->getOperand(0); 8093 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8094 unsigned Sz = VT.getScalarSizeInBits(); 8095 8096 SDValue Tmp, Tmp2, Tmp3; 8097 8098 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 8099 // and finally the i1 pairs. 8100 // TODO: We can easily support i4/i2 legal types if any target ever does. 8101 if (Sz >= 8 && isPowerOf2_32(Sz)) { 8102 // Create the masks - repeating the pattern every byte. 8103 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 8104 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 8105 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 8106 8107 // BSWAP if the type is wider than a single byte. 8108 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 8109 8110 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 8111 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 8112 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 8113 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 8114 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8115 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8116 8117 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8118 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8119 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8120 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8121 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8122 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8123 8124 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8125 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8126 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8127 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8128 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8129 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8130 return Tmp; 8131 } 8132 8133 Tmp = DAG.getConstant(0, dl, VT); 8134 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8135 if (I < J) 8136 Tmp2 = 8137 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8138 else 8139 Tmp2 = 8140 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8141 8142 APInt Shift(Sz, 1); 8143 Shift <<= J; 8144 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8145 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8146 } 8147 8148 return Tmp; 8149 } 8150 8151 std::pair<SDValue, SDValue> 8152 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8153 SelectionDAG &DAG) const { 8154 SDLoc SL(LD); 8155 SDValue Chain = LD->getChain(); 8156 SDValue BasePTR = LD->getBasePtr(); 8157 EVT SrcVT = LD->getMemoryVT(); 8158 EVT DstVT = LD->getValueType(0); 8159 ISD::LoadExtType ExtType = LD->getExtensionType(); 8160 8161 if (SrcVT.isScalableVector()) 8162 report_fatal_error("Cannot scalarize scalable vector loads"); 8163 8164 unsigned NumElem = SrcVT.getVectorNumElements(); 8165 8166 EVT SrcEltVT = SrcVT.getScalarType(); 8167 EVT DstEltVT = DstVT.getScalarType(); 8168 8169 // A vector must always be stored in memory as-is, i.e. without any padding 8170 // between the elements, since various code depend on it, e.g. in the 8171 // handling of a bitcast of a vector type to int, which may be done with a 8172 // vector store followed by an integer load. A vector that does not have 8173 // elements that are byte-sized must therefore be stored as an integer 8174 // built out of the extracted vector elements. 8175 if (!SrcEltVT.isByteSized()) { 8176 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8177 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8178 8179 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8180 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8181 8182 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8183 SDValue SrcEltBitMask = DAG.getConstant( 8184 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8185 8186 // Load the whole vector and avoid masking off the top bits as it makes 8187 // the codegen worse. 8188 SDValue Load = 8189 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8190 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8191 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8192 8193 SmallVector<SDValue, 8> Vals; 8194 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8195 unsigned ShiftIntoIdx = 8196 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8197 SDValue ShiftAmount = 8198 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8199 LoadVT, SL, /*LegalTypes=*/false); 8200 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8201 SDValue Elt = 8202 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8203 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8204 8205 if (ExtType != ISD::NON_EXTLOAD) { 8206 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8207 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8208 } 8209 8210 Vals.push_back(Scalar); 8211 } 8212 8213 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8214 return std::make_pair(Value, Load.getValue(1)); 8215 } 8216 8217 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8218 assert(SrcEltVT.isByteSized()); 8219 8220 SmallVector<SDValue, 8> Vals; 8221 SmallVector<SDValue, 8> LoadChains; 8222 8223 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8224 SDValue ScalarLoad = 8225 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8226 LD->getPointerInfo().getWithOffset(Idx * Stride), 8227 SrcEltVT, LD->getOriginalAlign(), 8228 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8229 8230 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8231 8232 Vals.push_back(ScalarLoad.getValue(0)); 8233 LoadChains.push_back(ScalarLoad.getValue(1)); 8234 } 8235 8236 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8237 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8238 8239 return std::make_pair(Value, NewChain); 8240 } 8241 8242 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8243 SelectionDAG &DAG) const { 8244 SDLoc SL(ST); 8245 8246 SDValue Chain = ST->getChain(); 8247 SDValue BasePtr = ST->getBasePtr(); 8248 SDValue Value = ST->getValue(); 8249 EVT StVT = ST->getMemoryVT(); 8250 8251 if (StVT.isScalableVector()) 8252 report_fatal_error("Cannot scalarize scalable vector stores"); 8253 8254 // The type of the data we want to save 8255 EVT RegVT = Value.getValueType(); 8256 EVT RegSclVT = RegVT.getScalarType(); 8257 8258 // The type of data as saved in memory. 8259 EVT MemSclVT = StVT.getScalarType(); 8260 8261 unsigned NumElem = StVT.getVectorNumElements(); 8262 8263 // A vector must always be stored in memory as-is, i.e. without any padding 8264 // between the elements, since various code depend on it, e.g. in the 8265 // handling of a bitcast of a vector type to int, which may be done with a 8266 // vector store followed by an integer load. A vector that does not have 8267 // elements that are byte-sized must therefore be stored as an integer 8268 // built out of the extracted vector elements. 8269 if (!MemSclVT.isByteSized()) { 8270 unsigned NumBits = StVT.getSizeInBits(); 8271 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8272 8273 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8274 8275 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8276 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8277 DAG.getVectorIdxConstant(Idx, SL)); 8278 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8279 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8280 unsigned ShiftIntoIdx = 8281 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8282 SDValue ShiftAmount = 8283 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8284 SDValue ShiftedElt = 8285 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8286 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8287 } 8288 8289 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8290 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8291 ST->getAAInfo()); 8292 } 8293 8294 // Store Stride in bytes 8295 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8296 assert(Stride && "Zero stride!"); 8297 // Extract each of the elements from the original vector and save them into 8298 // memory individually. 8299 SmallVector<SDValue, 8> Stores; 8300 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8301 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8302 DAG.getVectorIdxConstant(Idx, SL)); 8303 8304 SDValue Ptr = 8305 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8306 8307 // This scalar TruncStore may be illegal, but we legalize it later. 8308 SDValue Store = DAG.getTruncStore( 8309 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8310 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8311 ST->getAAInfo()); 8312 8313 Stores.push_back(Store); 8314 } 8315 8316 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8317 } 8318 8319 std::pair<SDValue, SDValue> 8320 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8321 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8322 "unaligned indexed loads not implemented!"); 8323 SDValue Chain = LD->getChain(); 8324 SDValue Ptr = LD->getBasePtr(); 8325 EVT VT = LD->getValueType(0); 8326 EVT LoadedVT = LD->getMemoryVT(); 8327 SDLoc dl(LD); 8328 auto &MF = DAG.getMachineFunction(); 8329 8330 if (VT.isFloatingPoint() || VT.isVector()) { 8331 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8332 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8333 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8334 LoadedVT.isVector()) { 8335 // Scalarize the load and let the individual components be handled. 8336 return scalarizeVectorLoad(LD, DAG); 8337 } 8338 8339 // Expand to a (misaligned) integer load of the same size, 8340 // then bitconvert to floating point or vector. 8341 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8342 LD->getMemOperand()); 8343 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8344 if (LoadedVT != VT) 8345 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8346 ISD::ANY_EXTEND, dl, VT, Result); 8347 8348 return std::make_pair(Result, newLoad.getValue(1)); 8349 } 8350 8351 // Copy the value to a (aligned) stack slot using (unaligned) integer 8352 // loads and stores, then do a (aligned) load from the stack slot. 8353 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8354 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8355 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8356 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8357 8358 // Make sure the stack slot is also aligned for the register type. 8359 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8360 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8361 SmallVector<SDValue, 8> Stores; 8362 SDValue StackPtr = StackBase; 8363 unsigned Offset = 0; 8364 8365 EVT PtrVT = Ptr.getValueType(); 8366 EVT StackPtrVT = StackPtr.getValueType(); 8367 8368 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8369 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8370 8371 // Do all but one copies using the full register width. 8372 for (unsigned i = 1; i < NumRegs; i++) { 8373 // Load one integer register's worth from the original location. 8374 SDValue Load = DAG.getLoad( 8375 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8376 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8377 LD->getAAInfo()); 8378 // Follow the load with a store to the stack slot. Remember the store. 8379 Stores.push_back(DAG.getStore( 8380 Load.getValue(1), dl, Load, StackPtr, 8381 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8382 // Increment the pointers. 8383 Offset += RegBytes; 8384 8385 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8386 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8387 } 8388 8389 // The last copy may be partial. Do an extending load. 8390 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8391 8 * (LoadedBytes - Offset)); 8392 SDValue Load = 8393 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8394 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8395 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8396 LD->getAAInfo()); 8397 // Follow the load with a store to the stack slot. Remember the store. 8398 // On big-endian machines this requires a truncating store to ensure 8399 // that the bits end up in the right place. 8400 Stores.push_back(DAG.getTruncStore( 8401 Load.getValue(1), dl, Load, StackPtr, 8402 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8403 8404 // The order of the stores doesn't matter - say it with a TokenFactor. 8405 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8406 8407 // Finally, perform the original load only redirected to the stack slot. 8408 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8409 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8410 LoadedVT); 8411 8412 // Callers expect a MERGE_VALUES node. 8413 return std::make_pair(Load, TF); 8414 } 8415 8416 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8417 "Unaligned load of unsupported type."); 8418 8419 // Compute the new VT that is half the size of the old one. This is an 8420 // integer MVT. 8421 unsigned NumBits = LoadedVT.getSizeInBits(); 8422 EVT NewLoadedVT; 8423 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8424 NumBits >>= 1; 8425 8426 Align Alignment = LD->getOriginalAlign(); 8427 unsigned IncrementSize = NumBits / 8; 8428 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8429 8430 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8431 if (HiExtType == ISD::NON_EXTLOAD) 8432 HiExtType = ISD::ZEXTLOAD; 8433 8434 // Load the value in two parts 8435 SDValue Lo, Hi; 8436 if (DAG.getDataLayout().isLittleEndian()) { 8437 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8438 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8439 LD->getAAInfo()); 8440 8441 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8442 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8443 LD->getPointerInfo().getWithOffset(IncrementSize), 8444 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8445 LD->getAAInfo()); 8446 } else { 8447 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8448 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8449 LD->getAAInfo()); 8450 8451 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8452 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8453 LD->getPointerInfo().getWithOffset(IncrementSize), 8454 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8455 LD->getAAInfo()); 8456 } 8457 8458 // aggregate the two parts 8459 SDValue ShiftAmount = 8460 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8461 DAG.getDataLayout())); 8462 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8463 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8464 8465 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8466 Hi.getValue(1)); 8467 8468 return std::make_pair(Result, TF); 8469 } 8470 8471 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8472 SelectionDAG &DAG) const { 8473 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8474 "unaligned indexed stores not implemented!"); 8475 SDValue Chain = ST->getChain(); 8476 SDValue Ptr = ST->getBasePtr(); 8477 SDValue Val = ST->getValue(); 8478 EVT VT = Val.getValueType(); 8479 Align Alignment = ST->getOriginalAlign(); 8480 auto &MF = DAG.getMachineFunction(); 8481 EVT StoreMemVT = ST->getMemoryVT(); 8482 8483 SDLoc dl(ST); 8484 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8485 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8486 if (isTypeLegal(intVT)) { 8487 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8488 StoreMemVT.isVector()) { 8489 // Scalarize the store and let the individual components be handled. 8490 SDValue Result = scalarizeVectorStore(ST, DAG); 8491 return Result; 8492 } 8493 // Expand to a bitconvert of the value to the integer type of the 8494 // same size, then a (misaligned) int store. 8495 // FIXME: Does not handle truncating floating point stores! 8496 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8497 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8498 Alignment, ST->getMemOperand()->getFlags()); 8499 return Result; 8500 } 8501 // Do a (aligned) store to a stack slot, then copy from the stack slot 8502 // to the final destination using (unaligned) integer loads and stores. 8503 MVT RegVT = getRegisterType( 8504 *DAG.getContext(), 8505 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8506 EVT PtrVT = Ptr.getValueType(); 8507 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8508 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8509 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8510 8511 // Make sure the stack slot is also aligned for the register type. 8512 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8513 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8514 8515 // Perform the original store, only redirected to the stack slot. 8516 SDValue Store = DAG.getTruncStore( 8517 Chain, dl, Val, StackPtr, 8518 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8519 8520 EVT StackPtrVT = StackPtr.getValueType(); 8521 8522 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8523 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8524 SmallVector<SDValue, 8> Stores; 8525 unsigned Offset = 0; 8526 8527 // Do all but one copies using the full register width. 8528 for (unsigned i = 1; i < NumRegs; i++) { 8529 // Load one integer register's worth from the stack slot. 8530 SDValue Load = DAG.getLoad( 8531 RegVT, dl, Store, StackPtr, 8532 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8533 // Store it to the final location. Remember the store. 8534 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8535 ST->getPointerInfo().getWithOffset(Offset), 8536 ST->getOriginalAlign(), 8537 ST->getMemOperand()->getFlags())); 8538 // Increment the pointers. 8539 Offset += RegBytes; 8540 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8541 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8542 } 8543 8544 // The last store may be partial. Do a truncating store. On big-endian 8545 // machines this requires an extending load from the stack slot to ensure 8546 // that the bits are in the right place. 8547 EVT LoadMemVT = 8548 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8549 8550 // Load from the stack slot. 8551 SDValue Load = DAG.getExtLoad( 8552 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8553 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8554 8555 Stores.push_back( 8556 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8557 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8558 ST->getOriginalAlign(), 8559 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8560 // The order of the stores doesn't matter - say it with a TokenFactor. 8561 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8562 return Result; 8563 } 8564 8565 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8566 "Unaligned store of unknown type."); 8567 // Get the half-size VT 8568 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8569 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8570 unsigned IncrementSize = NumBits / 8; 8571 8572 // Divide the stored value in two parts. 8573 SDValue ShiftAmount = DAG.getConstant( 8574 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8575 SDValue Lo = Val; 8576 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8577 8578 // Store the two parts 8579 SDValue Store1, Store2; 8580 Store1 = DAG.getTruncStore(Chain, dl, 8581 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8582 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8583 ST->getMemOperand()->getFlags()); 8584 8585 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8586 Store2 = DAG.getTruncStore( 8587 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8588 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8589 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8590 8591 SDValue Result = 8592 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8593 return Result; 8594 } 8595 8596 SDValue 8597 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8598 const SDLoc &DL, EVT DataVT, 8599 SelectionDAG &DAG, 8600 bool IsCompressedMemory) const { 8601 SDValue Increment; 8602 EVT AddrVT = Addr.getValueType(); 8603 EVT MaskVT = Mask.getValueType(); 8604 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8605 "Incompatible types of Data and Mask"); 8606 if (IsCompressedMemory) { 8607 if (DataVT.isScalableVector()) 8608 report_fatal_error( 8609 "Cannot currently handle compressed memory with scalable vectors"); 8610 // Incrementing the pointer according to number of '1's in the mask. 8611 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8612 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8613 if (MaskIntVT.getSizeInBits() < 32) { 8614 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8615 MaskIntVT = MVT::i32; 8616 } 8617 8618 // Count '1's with POPCNT. 8619 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8620 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8621 // Scale is an element size in bytes. 8622 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8623 AddrVT); 8624 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8625 } else if (DataVT.isScalableVector()) { 8626 Increment = DAG.getVScale(DL, AddrVT, 8627 APInt(AddrVT.getFixedSizeInBits(), 8628 DataVT.getStoreSize().getKnownMinSize())); 8629 } else 8630 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8631 8632 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8633 } 8634 8635 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8636 EVT VecVT, const SDLoc &dl, 8637 ElementCount SubEC) { 8638 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8639 "Cannot index a scalable vector within a fixed-width vector"); 8640 8641 unsigned NElts = VecVT.getVectorMinNumElements(); 8642 unsigned NumSubElts = SubEC.getKnownMinValue(); 8643 EVT IdxVT = Idx.getValueType(); 8644 8645 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8646 // If this is a constant index and we know the value plus the number of the 8647 // elements in the subvector minus one is less than the minimum number of 8648 // elements then it's safe to return Idx. 8649 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8650 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8651 return Idx; 8652 SDValue VS = 8653 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8654 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8655 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8656 DAG.getConstant(NumSubElts, dl, IdxVT)); 8657 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8658 } 8659 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8660 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8661 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8662 DAG.getConstant(Imm, dl, IdxVT)); 8663 } 8664 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8665 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8666 DAG.getConstant(MaxIndex, dl, IdxVT)); 8667 } 8668 8669 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8670 SDValue VecPtr, EVT VecVT, 8671 SDValue Index) const { 8672 return getVectorSubVecPointer( 8673 DAG, VecPtr, VecVT, 8674 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8675 Index); 8676 } 8677 8678 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8679 SDValue VecPtr, EVT VecVT, 8680 EVT SubVecVT, 8681 SDValue Index) const { 8682 SDLoc dl(Index); 8683 // Make sure the index type is big enough to compute in. 8684 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8685 8686 EVT EltVT = VecVT.getVectorElementType(); 8687 8688 // Calculate the element offset and add it to the pointer. 8689 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8690 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8691 "Converting bits to bytes lost precision"); 8692 assert(SubVecVT.getVectorElementType() == EltVT && 8693 "Sub-vector must be a vector with matching element type"); 8694 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8695 SubVecVT.getVectorElementCount()); 8696 8697 EVT IdxVT = Index.getValueType(); 8698 if (SubVecVT.isScalableVector()) 8699 Index = 8700 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8701 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8702 8703 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8704 DAG.getConstant(EltSize, dl, IdxVT)); 8705 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8706 } 8707 8708 //===----------------------------------------------------------------------===// 8709 // Implementation of Emulated TLS Model 8710 //===----------------------------------------------------------------------===// 8711 8712 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8713 SelectionDAG &DAG) const { 8714 // Access to address of TLS varialbe xyz is lowered to a function call: 8715 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8716 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8717 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8718 SDLoc dl(GA); 8719 8720 ArgListTy Args; 8721 ArgListEntry Entry; 8722 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8723 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8724 StringRef EmuTlsVarName(NameString); 8725 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8726 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8727 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8728 Entry.Ty = VoidPtrType; 8729 Args.push_back(Entry); 8730 8731 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8732 8733 TargetLowering::CallLoweringInfo CLI(DAG); 8734 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8735 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8736 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8737 8738 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8739 // At last for X86 targets, maybe good for other targets too? 8740 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8741 MFI.setAdjustsStack(true); // Is this only for X86 target? 8742 MFI.setHasCalls(true); 8743 8744 assert((GA->getOffset() == 0) && 8745 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8746 return CallResult.first; 8747 } 8748 8749 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8750 SelectionDAG &DAG) const { 8751 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8752 if (!isCtlzFast()) 8753 return SDValue(); 8754 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8755 SDLoc dl(Op); 8756 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8757 if (C->isZero() && CC == ISD::SETEQ) { 8758 EVT VT = Op.getOperand(0).getValueType(); 8759 SDValue Zext = Op.getOperand(0); 8760 if (VT.bitsLT(MVT::i32)) { 8761 VT = MVT::i32; 8762 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8763 } 8764 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8765 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8766 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8767 DAG.getConstant(Log2b, dl, MVT::i32)); 8768 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8769 } 8770 } 8771 return SDValue(); 8772 } 8773 8774 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8775 SDValue Op0 = Node->getOperand(0); 8776 SDValue Op1 = Node->getOperand(1); 8777 EVT VT = Op0.getValueType(); 8778 unsigned Opcode = Node->getOpcode(); 8779 SDLoc DL(Node); 8780 8781 // umin(x,y) -> sub(x,usubsat(x,y)) 8782 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8783 isOperationLegal(ISD::USUBSAT, VT)) { 8784 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8785 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8786 } 8787 8788 // umax(x,y) -> add(x,usubsat(y,x)) 8789 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8790 isOperationLegal(ISD::USUBSAT, VT)) { 8791 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8792 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8793 } 8794 8795 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8796 ISD::CondCode CC; 8797 switch (Opcode) { 8798 default: llvm_unreachable("How did we get here?"); 8799 case ISD::SMAX: CC = ISD::SETGT; break; 8800 case ISD::SMIN: CC = ISD::SETLT; break; 8801 case ISD::UMAX: CC = ISD::SETUGT; break; 8802 case ISD::UMIN: CC = ISD::SETULT; break; 8803 } 8804 8805 // FIXME: Should really try to split the vector in case it's legal on a 8806 // subvector. 8807 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8808 return DAG.UnrollVectorOp(Node); 8809 8810 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8811 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8812 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8813 } 8814 8815 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8816 unsigned Opcode = Node->getOpcode(); 8817 SDValue LHS = Node->getOperand(0); 8818 SDValue RHS = Node->getOperand(1); 8819 EVT VT = LHS.getValueType(); 8820 SDLoc dl(Node); 8821 8822 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8823 assert(VT.isInteger() && "Expected operands to be integers"); 8824 8825 // usub.sat(a, b) -> umax(a, b) - b 8826 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8827 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8828 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8829 } 8830 8831 // uadd.sat(a, b) -> umin(a, ~b) + b 8832 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8833 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8834 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8835 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8836 } 8837 8838 unsigned OverflowOp; 8839 switch (Opcode) { 8840 case ISD::SADDSAT: 8841 OverflowOp = ISD::SADDO; 8842 break; 8843 case ISD::UADDSAT: 8844 OverflowOp = ISD::UADDO; 8845 break; 8846 case ISD::SSUBSAT: 8847 OverflowOp = ISD::SSUBO; 8848 break; 8849 case ISD::USUBSAT: 8850 OverflowOp = ISD::USUBO; 8851 break; 8852 default: 8853 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8854 "addition or subtraction node."); 8855 } 8856 8857 // FIXME: Should really try to split the vector in case it's legal on a 8858 // subvector. 8859 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8860 return DAG.UnrollVectorOp(Node); 8861 8862 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8863 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8864 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8865 SDValue SumDiff = Result.getValue(0); 8866 SDValue Overflow = Result.getValue(1); 8867 SDValue Zero = DAG.getConstant(0, dl, VT); 8868 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8869 8870 if (Opcode == ISD::UADDSAT) { 8871 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8872 // (LHS + RHS) | OverflowMask 8873 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8874 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8875 } 8876 // Overflow ? 0xffff.... : (LHS + RHS) 8877 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8878 } 8879 8880 if (Opcode == ISD::USUBSAT) { 8881 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8882 // (LHS - RHS) & ~OverflowMask 8883 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8884 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8885 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8886 } 8887 // Overflow ? 0 : (LHS - RHS) 8888 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8889 } 8890 8891 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8892 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8893 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8894 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8895 DAG.getConstant(BitWidth - 1, dl, VT)); 8896 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8897 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8898 } 8899 8900 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8901 unsigned Opcode = Node->getOpcode(); 8902 bool IsSigned = Opcode == ISD::SSHLSAT; 8903 SDValue LHS = Node->getOperand(0); 8904 SDValue RHS = Node->getOperand(1); 8905 EVT VT = LHS.getValueType(); 8906 SDLoc dl(Node); 8907 8908 assert((Node->getOpcode() == ISD::SSHLSAT || 8909 Node->getOpcode() == ISD::USHLSAT) && 8910 "Expected a SHLSAT opcode"); 8911 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8912 assert(VT.isInteger() && "Expected operands to be integers"); 8913 8914 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8915 8916 unsigned BW = VT.getScalarSizeInBits(); 8917 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8918 SDValue Orig = 8919 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8920 8921 SDValue SatVal; 8922 if (IsSigned) { 8923 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8924 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8925 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8926 SatMin, SatMax, ISD::SETLT); 8927 } else { 8928 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8929 } 8930 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8931 8932 return Result; 8933 } 8934 8935 SDValue 8936 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8937 assert((Node->getOpcode() == ISD::SMULFIX || 8938 Node->getOpcode() == ISD::UMULFIX || 8939 Node->getOpcode() == ISD::SMULFIXSAT || 8940 Node->getOpcode() == ISD::UMULFIXSAT) && 8941 "Expected a fixed point multiplication opcode"); 8942 8943 SDLoc dl(Node); 8944 SDValue LHS = Node->getOperand(0); 8945 SDValue RHS = Node->getOperand(1); 8946 EVT VT = LHS.getValueType(); 8947 unsigned Scale = Node->getConstantOperandVal(2); 8948 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8949 Node->getOpcode() == ISD::UMULFIXSAT); 8950 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8951 Node->getOpcode() == ISD::SMULFIXSAT); 8952 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8953 unsigned VTSize = VT.getScalarSizeInBits(); 8954 8955 if (!Scale) { 8956 // [us]mul.fix(a, b, 0) -> mul(a, b) 8957 if (!Saturating) { 8958 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8959 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8960 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8961 SDValue Result = 8962 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8963 SDValue Product = Result.getValue(0); 8964 SDValue Overflow = Result.getValue(1); 8965 SDValue Zero = DAG.getConstant(0, dl, VT); 8966 8967 APInt MinVal = APInt::getSignedMinValue(VTSize); 8968 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8969 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8970 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8971 // Xor the inputs, if resulting sign bit is 0 the product will be 8972 // positive, else negative. 8973 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8974 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8975 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8976 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8977 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8978 SDValue Result = 8979 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8980 SDValue Product = Result.getValue(0); 8981 SDValue Overflow = Result.getValue(1); 8982 8983 APInt MaxVal = APInt::getMaxValue(VTSize); 8984 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8985 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8986 } 8987 } 8988 8989 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8990 "Expected scale to be less than the number of bits if signed or at " 8991 "most the number of bits if unsigned."); 8992 assert(LHS.getValueType() == RHS.getValueType() && 8993 "Expected both operands to be the same type"); 8994 8995 // Get the upper and lower bits of the result. 8996 SDValue Lo, Hi; 8997 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8998 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8999 if (isOperationLegalOrCustom(LoHiOp, VT)) { 9000 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 9001 Lo = Result.getValue(0); 9002 Hi = Result.getValue(1); 9003 } else if (isOperationLegalOrCustom(HiOp, VT)) { 9004 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9005 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 9006 } else if (VT.isVector()) { 9007 return SDValue(); 9008 } else { 9009 report_fatal_error("Unable to expand fixed point multiplication."); 9010 } 9011 9012 if (Scale == VTSize) 9013 // Result is just the top half since we'd be shifting by the width of the 9014 // operand. Overflow impossible so this works for both UMULFIX and 9015 // UMULFIXSAT. 9016 return Hi; 9017 9018 // The result will need to be shifted right by the scale since both operands 9019 // are scaled. The result is given to us in 2 halves, so we only want part of 9020 // both in the result. 9021 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9022 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 9023 DAG.getConstant(Scale, dl, ShiftTy)); 9024 if (!Saturating) 9025 return Result; 9026 9027 if (!Signed) { 9028 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 9029 // widened multiplication) aren't all zeroes. 9030 9031 // Saturate to max if ((Hi >> Scale) != 0), 9032 // which is the same as if (Hi > ((1 << Scale) - 1)) 9033 APInt MaxVal = APInt::getMaxValue(VTSize); 9034 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 9035 dl, VT); 9036 Result = DAG.getSelectCC(dl, Hi, LowMask, 9037 DAG.getConstant(MaxVal, dl, VT), Result, 9038 ISD::SETUGT); 9039 9040 return Result; 9041 } 9042 9043 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 9044 // widened multiplication) aren't all ones or all zeroes. 9045 9046 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 9047 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 9048 9049 if (Scale == 0) { 9050 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 9051 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 9052 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 9053 // Saturated to SatMin if wide product is negative, and SatMax if wide 9054 // product is positive ... 9055 SDValue Zero = DAG.getConstant(0, dl, VT); 9056 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 9057 ISD::SETLT); 9058 // ... but only if we overflowed. 9059 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 9060 } 9061 9062 // We handled Scale==0 above so all the bits to examine is in Hi. 9063 9064 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 9065 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 9066 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 9067 dl, VT); 9068 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 9069 // Saturate to min if (Hi >> (Scale - 1)) < -1), 9070 // which is the same as if (HI < (-1 << (Scale - 1)) 9071 SDValue HighMask = 9072 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 9073 dl, VT); 9074 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 9075 return Result; 9076 } 9077 9078 SDValue 9079 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 9080 SDValue LHS, SDValue RHS, 9081 unsigned Scale, SelectionDAG &DAG) const { 9082 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 9083 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 9084 "Expected a fixed point division opcode"); 9085 9086 EVT VT = LHS.getValueType(); 9087 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 9088 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 9089 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9090 9091 // If there is enough room in the type to upscale the LHS or downscale the 9092 // RHS before the division, we can perform it in this type without having to 9093 // resize. For signed operations, the LHS headroom is the number of 9094 // redundant sign bits, and for unsigned ones it is the number of zeroes. 9095 // The headroom for the RHS is the number of trailing zeroes. 9096 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 9097 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 9098 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 9099 9100 // For signed saturating operations, we need to be able to detect true integer 9101 // division overflow; that is, when you have MIN / -EPS. However, this 9102 // is undefined behavior and if we emit divisions that could take such 9103 // values it may cause undesired behavior (arithmetic exceptions on x86, for 9104 // example). 9105 // Avoid this by requiring an extra bit so that we never get this case. 9106 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 9107 // signed saturating division, we need to emit a whopping 32-bit division. 9108 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 9109 return SDValue(); 9110 9111 unsigned LHSShift = std::min(LHSLead, Scale); 9112 unsigned RHSShift = Scale - LHSShift; 9113 9114 // At this point, we know that if we shift the LHS up by LHSShift and the 9115 // RHS down by RHSShift, we can emit a regular division with a final scaling 9116 // factor of Scale. 9117 9118 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9119 if (LHSShift) 9120 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9121 DAG.getConstant(LHSShift, dl, ShiftTy)); 9122 if (RHSShift) 9123 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9124 DAG.getConstant(RHSShift, dl, ShiftTy)); 9125 9126 SDValue Quot; 9127 if (Signed) { 9128 // For signed operations, if the resulting quotient is negative and the 9129 // remainder is nonzero, subtract 1 from the quotient to round towards 9130 // negative infinity. 9131 SDValue Rem; 9132 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9133 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9134 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9135 if (isTypeLegal(VT) && 9136 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9137 Quot = DAG.getNode(ISD::SDIVREM, dl, 9138 DAG.getVTList(VT, VT), 9139 LHS, RHS); 9140 Rem = Quot.getValue(1); 9141 Quot = Quot.getValue(0); 9142 } else { 9143 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9144 LHS, RHS); 9145 Rem = DAG.getNode(ISD::SREM, dl, VT, 9146 LHS, RHS); 9147 } 9148 SDValue Zero = DAG.getConstant(0, dl, VT); 9149 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9150 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9151 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9152 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9153 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9154 DAG.getConstant(1, dl, VT)); 9155 Quot = DAG.getSelect(dl, VT, 9156 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9157 Sub1, Quot); 9158 } else 9159 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9160 LHS, RHS); 9161 9162 return Quot; 9163 } 9164 9165 void TargetLowering::expandUADDSUBO( 9166 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9167 SDLoc dl(Node); 9168 SDValue LHS = Node->getOperand(0); 9169 SDValue RHS = Node->getOperand(1); 9170 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9171 9172 // If ADD/SUBCARRY is legal, use that instead. 9173 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9174 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9175 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9176 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9177 { LHS, RHS, CarryIn }); 9178 Result = SDValue(NodeCarry.getNode(), 0); 9179 Overflow = SDValue(NodeCarry.getNode(), 1); 9180 return; 9181 } 9182 9183 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9184 LHS.getValueType(), LHS, RHS); 9185 9186 EVT ResultType = Node->getValueType(1); 9187 EVT SetCCType = getSetCCResultType( 9188 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9189 SDValue SetCC; 9190 if (IsAdd && isOneConstant(RHS)) { 9191 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9192 // the live range of X. We assume comparing with 0 is cheap. 9193 // The general case (X + C) < C is not necessarily beneficial. Although we 9194 // reduce the live range of X, we may introduce the materialization of 9195 // constant C. 9196 SetCC = 9197 DAG.getSetCC(dl, SetCCType, Result, 9198 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9199 } else { 9200 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9201 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9202 } 9203 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9204 } 9205 9206 void TargetLowering::expandSADDSUBO( 9207 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9208 SDLoc dl(Node); 9209 SDValue LHS = Node->getOperand(0); 9210 SDValue RHS = Node->getOperand(1); 9211 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9212 9213 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9214 LHS.getValueType(), LHS, RHS); 9215 9216 EVT ResultType = Node->getValueType(1); 9217 EVT OType = getSetCCResultType( 9218 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9219 9220 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9221 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9222 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9223 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9224 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9225 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9226 return; 9227 } 9228 9229 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9230 9231 // For an addition, the result should be less than one of the operands (LHS) 9232 // if and only if the other operand (RHS) is negative, otherwise there will 9233 // be overflow. 9234 // For a subtraction, the result should be less than one of the operands 9235 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9236 // otherwise there will be overflow. 9237 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9238 SDValue ConditionRHS = 9239 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9240 9241 Overflow = DAG.getBoolExtOrTrunc( 9242 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9243 ResultType, ResultType); 9244 } 9245 9246 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9247 SDValue &Overflow, SelectionDAG &DAG) const { 9248 SDLoc dl(Node); 9249 EVT VT = Node->getValueType(0); 9250 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9251 SDValue LHS = Node->getOperand(0); 9252 SDValue RHS = Node->getOperand(1); 9253 bool isSigned = Node->getOpcode() == ISD::SMULO; 9254 9255 // For power-of-two multiplications we can use a simpler shift expansion. 9256 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9257 const APInt &C = RHSC->getAPIntValue(); 9258 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9259 if (C.isPowerOf2()) { 9260 // smulo(x, signed_min) is same as umulo(x, signed_min). 9261 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9262 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9263 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9264 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9265 Overflow = DAG.getSetCC(dl, SetCCVT, 9266 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9267 dl, VT, Result, ShiftAmt), 9268 LHS, ISD::SETNE); 9269 return true; 9270 } 9271 } 9272 9273 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9274 if (VT.isVector()) 9275 WideVT = 9276 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9277 9278 SDValue BottomHalf; 9279 SDValue TopHalf; 9280 static const unsigned Ops[2][3] = 9281 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9282 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9283 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9284 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9285 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9286 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9287 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9288 RHS); 9289 TopHalf = BottomHalf.getValue(1); 9290 } else if (isTypeLegal(WideVT)) { 9291 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9292 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9293 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9294 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9295 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9296 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9297 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9298 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9299 } else { 9300 if (VT.isVector()) 9301 return false; 9302 9303 // We can fall back to a libcall with an illegal type for the MUL if we 9304 // have a libcall big enough. 9305 // Also, we can fall back to a division in some cases, but that's a big 9306 // performance hit in the general case. 9307 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9308 if (WideVT == MVT::i16) 9309 LC = RTLIB::MUL_I16; 9310 else if (WideVT == MVT::i32) 9311 LC = RTLIB::MUL_I32; 9312 else if (WideVT == MVT::i64) 9313 LC = RTLIB::MUL_I64; 9314 else if (WideVT == MVT::i128) 9315 LC = RTLIB::MUL_I128; 9316 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9317 9318 SDValue HiLHS; 9319 SDValue HiRHS; 9320 if (isSigned) { 9321 // The high part is obtained by SRA'ing all but one of the bits of low 9322 // part. 9323 unsigned LoSize = VT.getFixedSizeInBits(); 9324 HiLHS = 9325 DAG.getNode(ISD::SRA, dl, VT, LHS, 9326 DAG.getConstant(LoSize - 1, dl, 9327 getPointerTy(DAG.getDataLayout()))); 9328 HiRHS = 9329 DAG.getNode(ISD::SRA, dl, VT, RHS, 9330 DAG.getConstant(LoSize - 1, dl, 9331 getPointerTy(DAG.getDataLayout()))); 9332 } else { 9333 HiLHS = DAG.getConstant(0, dl, VT); 9334 HiRHS = DAG.getConstant(0, dl, VT); 9335 } 9336 9337 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9338 // pre-lowered to the correct types. This all depends upon WideVT not 9339 // being a legal type for the architecture and thus has to be split to 9340 // two arguments. 9341 SDValue Ret; 9342 TargetLowering::MakeLibCallOptions CallOptions; 9343 CallOptions.setSExt(isSigned); 9344 CallOptions.setIsPostTypeLegalization(true); 9345 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9346 // Halves of WideVT are packed into registers in different order 9347 // depending on platform endianness. This is usually handled by 9348 // the C calling convention, but we can't defer to it in 9349 // the legalizer. 9350 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9351 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9352 } else { 9353 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9354 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9355 } 9356 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9357 "Ret value is a collection of constituent nodes holding result."); 9358 if (DAG.getDataLayout().isLittleEndian()) { 9359 // Same as above. 9360 BottomHalf = Ret.getOperand(0); 9361 TopHalf = Ret.getOperand(1); 9362 } else { 9363 BottomHalf = Ret.getOperand(1); 9364 TopHalf = Ret.getOperand(0); 9365 } 9366 } 9367 9368 Result = BottomHalf; 9369 if (isSigned) { 9370 SDValue ShiftAmt = DAG.getConstant( 9371 VT.getScalarSizeInBits() - 1, dl, 9372 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9373 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9374 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9375 } else { 9376 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9377 DAG.getConstant(0, dl, VT), ISD::SETNE); 9378 } 9379 9380 // Truncate the result if SetCC returns a larger type than needed. 9381 EVT RType = Node->getValueType(1); 9382 if (RType.bitsLT(Overflow.getValueType())) 9383 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9384 9385 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9386 "Unexpected result type for S/UMULO legalization"); 9387 return true; 9388 } 9389 9390 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9391 SDLoc dl(Node); 9392 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9393 SDValue Op = Node->getOperand(0); 9394 EVT VT = Op.getValueType(); 9395 9396 if (VT.isScalableVector()) 9397 report_fatal_error( 9398 "Expanding reductions for scalable vectors is undefined."); 9399 9400 // Try to use a shuffle reduction for power of two vectors. 9401 if (VT.isPow2VectorType()) { 9402 while (VT.getVectorNumElements() > 1) { 9403 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9404 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9405 break; 9406 9407 SDValue Lo, Hi; 9408 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9409 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9410 VT = HalfVT; 9411 } 9412 } 9413 9414 EVT EltVT = VT.getVectorElementType(); 9415 unsigned NumElts = VT.getVectorNumElements(); 9416 9417 SmallVector<SDValue, 8> Ops; 9418 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9419 9420 SDValue Res = Ops[0]; 9421 for (unsigned i = 1; i < NumElts; i++) 9422 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9423 9424 // Result type may be wider than element type. 9425 if (EltVT != Node->getValueType(0)) 9426 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9427 return Res; 9428 } 9429 9430 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9431 SDLoc dl(Node); 9432 SDValue AccOp = Node->getOperand(0); 9433 SDValue VecOp = Node->getOperand(1); 9434 SDNodeFlags Flags = Node->getFlags(); 9435 9436 EVT VT = VecOp.getValueType(); 9437 EVT EltVT = VT.getVectorElementType(); 9438 9439 if (VT.isScalableVector()) 9440 report_fatal_error( 9441 "Expanding reductions for scalable vectors is undefined."); 9442 9443 unsigned NumElts = VT.getVectorNumElements(); 9444 9445 SmallVector<SDValue, 8> Ops; 9446 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9447 9448 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9449 9450 SDValue Res = AccOp; 9451 for (unsigned i = 0; i < NumElts; i++) 9452 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9453 9454 return Res; 9455 } 9456 9457 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9458 SelectionDAG &DAG) const { 9459 EVT VT = Node->getValueType(0); 9460 SDLoc dl(Node); 9461 bool isSigned = Node->getOpcode() == ISD::SREM; 9462 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9463 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9464 SDValue Dividend = Node->getOperand(0); 9465 SDValue Divisor = Node->getOperand(1); 9466 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9467 SDVTList VTs = DAG.getVTList(VT, VT); 9468 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9469 return true; 9470 } 9471 if (isOperationLegalOrCustom(DivOpc, VT)) { 9472 // X % Y -> X-X/Y*Y 9473 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9474 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9475 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9476 return true; 9477 } 9478 return false; 9479 } 9480 9481 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9482 SelectionDAG &DAG) const { 9483 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9484 SDLoc dl(SDValue(Node, 0)); 9485 SDValue Src = Node->getOperand(0); 9486 9487 // DstVT is the result type, while SatVT is the size to which we saturate 9488 EVT SrcVT = Src.getValueType(); 9489 EVT DstVT = Node->getValueType(0); 9490 9491 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9492 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9493 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9494 assert(SatWidth <= DstWidth && 9495 "Expected saturation width smaller than result width"); 9496 9497 // Determine minimum and maximum integer values and their corresponding 9498 // floating-point values. 9499 APInt MinInt, MaxInt; 9500 if (IsSigned) { 9501 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9502 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9503 } else { 9504 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9505 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9506 } 9507 9508 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9509 // libcall emission cannot handle this. Large result types will fail. 9510 if (SrcVT == MVT::f16) { 9511 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9512 SrcVT = Src.getValueType(); 9513 } 9514 9515 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9516 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9517 9518 APFloat::opStatus MinStatus = 9519 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9520 APFloat::opStatus MaxStatus = 9521 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9522 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9523 !(MaxStatus & APFloat::opStatus::opInexact); 9524 9525 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9526 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9527 9528 // If the integer bounds are exactly representable as floats and min/max are 9529 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9530 // of comparisons and selects. 9531 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9532 isOperationLegal(ISD::FMAXNUM, SrcVT); 9533 if (AreExactFloatBounds && MinMaxLegal) { 9534 SDValue Clamped = Src; 9535 9536 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9537 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9538 // Clamp by MaxFloat from above. NaN cannot occur. 9539 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9540 // Convert clamped value to integer. 9541 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9542 dl, DstVT, Clamped); 9543 9544 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9545 // which will cast to zero. 9546 if (!IsSigned) 9547 return FpToInt; 9548 9549 // Otherwise, select 0 if Src is NaN. 9550 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9551 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9552 ISD::CondCode::SETUO); 9553 } 9554 9555 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9556 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9557 9558 // Result of direct conversion. The assumption here is that the operation is 9559 // non-trapping and it's fine to apply it to an out-of-range value if we 9560 // select it away later. 9561 SDValue FpToInt = 9562 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9563 9564 SDValue Select = FpToInt; 9565 9566 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9567 // MinInt if Src is NaN. 9568 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9569 ISD::CondCode::SETULT); 9570 // If Src OGT MaxFloat, select MaxInt. 9571 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9572 ISD::CondCode::SETOGT); 9573 9574 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9575 // is already zero. 9576 if (!IsSigned) 9577 return Select; 9578 9579 // Otherwise, select 0 if Src is NaN. 9580 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9581 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9582 } 9583 9584 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9585 SelectionDAG &DAG) const { 9586 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9587 assert(Node->getValueType(0).isScalableVector() && 9588 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9589 9590 EVT VT = Node->getValueType(0); 9591 SDValue V1 = Node->getOperand(0); 9592 SDValue V2 = Node->getOperand(1); 9593 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9594 SDLoc DL(Node); 9595 9596 // Expand through memory thusly: 9597 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9598 // Store V1, Ptr 9599 // Store V2, Ptr + sizeof(V1) 9600 // If (Imm < 0) 9601 // TrailingElts = -Imm 9602 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9603 // else 9604 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9605 // Res = Load Ptr 9606 9607 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9608 9609 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9610 VT.getVectorElementCount() * 2); 9611 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9612 EVT PtrVT = StackPtr.getValueType(); 9613 auto &MF = DAG.getMachineFunction(); 9614 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9615 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9616 9617 // Store the lo part of CONCAT_VECTORS(V1, V2) 9618 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9619 // Store the hi part of CONCAT_VECTORS(V1, V2) 9620 SDValue OffsetToV2 = DAG.getVScale( 9621 DL, PtrVT, 9622 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9623 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9624 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9625 9626 if (Imm >= 0) { 9627 // Load back the required element. getVectorElementPointer takes care of 9628 // clamping the index if it's out-of-bounds. 9629 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9630 // Load the spliced result 9631 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9632 MachinePointerInfo::getUnknownStack(MF)); 9633 } 9634 9635 uint64_t TrailingElts = -Imm; 9636 9637 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9638 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9639 SDValue TrailingBytes = 9640 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9641 9642 if (TrailingElts > VT.getVectorMinNumElements()) { 9643 SDValue VLBytes = DAG.getVScale( 9644 DL, PtrVT, 9645 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9646 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9647 } 9648 9649 // Calculate the start address of the spliced result. 9650 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9651 9652 // Load the spliced result 9653 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9654 MachinePointerInfo::getUnknownStack(MF)); 9655 } 9656 9657 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9658 SDValue &LHS, SDValue &RHS, 9659 SDValue &CC, SDValue Mask, 9660 SDValue EVL, bool &NeedInvert, 9661 const SDLoc &dl, SDValue &Chain, 9662 bool IsSignaling) const { 9663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9664 MVT OpVT = LHS.getSimpleValueType(); 9665 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9666 NeedInvert = false; 9667 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9668 bool IsNonVP = !EVL; 9669 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9670 default: 9671 llvm_unreachable("Unknown condition code action!"); 9672 case TargetLowering::Legal: 9673 // Nothing to do. 9674 break; 9675 case TargetLowering::Expand: { 9676 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9677 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9678 std::swap(LHS, RHS); 9679 CC = DAG.getCondCode(InvCC); 9680 return true; 9681 } 9682 // Swapping operands didn't work. Try inverting the condition. 9683 bool NeedSwap = false; 9684 InvCC = getSetCCInverse(CCCode, OpVT); 9685 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9686 // If inverting the condition is not enough, try swapping operands 9687 // on top of it. 9688 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9689 NeedSwap = true; 9690 } 9691 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9692 CC = DAG.getCondCode(InvCC); 9693 NeedInvert = true; 9694 if (NeedSwap) 9695 std::swap(LHS, RHS); 9696 return true; 9697 } 9698 9699 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9700 unsigned Opc = 0; 9701 switch (CCCode) { 9702 default: 9703 llvm_unreachable("Don't know how to expand this condition!"); 9704 case ISD::SETUO: 9705 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9706 CC1 = ISD::SETUNE; 9707 CC2 = ISD::SETUNE; 9708 Opc = ISD::OR; 9709 break; 9710 } 9711 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9712 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9713 NeedInvert = true; 9714 LLVM_FALLTHROUGH; 9715 case ISD::SETO: 9716 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9717 "If SETO is expanded, SETOEQ must be legal!"); 9718 CC1 = ISD::SETOEQ; 9719 CC2 = ISD::SETOEQ; 9720 Opc = ISD::AND; 9721 break; 9722 case ISD::SETONE: 9723 case ISD::SETUEQ: 9724 // If the SETUO or SETO CC isn't legal, we might be able to use 9725 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9726 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9727 // the operands. 9728 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9729 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9730 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9731 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9732 CC1 = ISD::SETOGT; 9733 CC2 = ISD::SETOLT; 9734 Opc = ISD::OR; 9735 NeedInvert = ((unsigned)CCCode & 0x8U); 9736 break; 9737 } 9738 LLVM_FALLTHROUGH; 9739 case ISD::SETOEQ: 9740 case ISD::SETOGT: 9741 case ISD::SETOGE: 9742 case ISD::SETOLT: 9743 case ISD::SETOLE: 9744 case ISD::SETUNE: 9745 case ISD::SETUGT: 9746 case ISD::SETUGE: 9747 case ISD::SETULT: 9748 case ISD::SETULE: 9749 // If we are floating point, assign and break, otherwise fall through. 9750 if (!OpVT.isInteger()) { 9751 // We can use the 4th bit to tell if we are the unordered 9752 // or ordered version of the opcode. 9753 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9754 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9755 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9756 break; 9757 } 9758 // Fallthrough if we are unsigned integer. 9759 LLVM_FALLTHROUGH; 9760 case ISD::SETLE: 9761 case ISD::SETGT: 9762 case ISD::SETGE: 9763 case ISD::SETLT: 9764 case ISD::SETNE: 9765 case ISD::SETEQ: 9766 // If all combinations of inverting the condition and swapping operands 9767 // didn't work then we have no means to expand the condition. 9768 llvm_unreachable("Don't know how to expand this condition!"); 9769 } 9770 9771 SDValue SetCC1, SetCC2; 9772 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9773 // If we aren't the ordered or unorder operation, 9774 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9775 if (IsNonVP) { 9776 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9777 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9778 } else { 9779 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9780 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9781 } 9782 } else { 9783 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9784 if (IsNonVP) { 9785 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9786 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9787 } else { 9788 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9789 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9790 } 9791 } 9792 if (Chain) 9793 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9794 SetCC2.getValue(1)); 9795 if (IsNonVP) 9796 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9797 else { 9798 // Transform the binary opcode to the VP equivalent. 9799 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9800 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9801 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9802 } 9803 RHS = SDValue(); 9804 CC = SDValue(); 9805 return true; 9806 } 9807 } 9808 return false; 9809 } 9810