1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/TargetLowering.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/CodeGen/CallingConvLower.h" 16 #include "llvm/CodeGen/MachineFrameInfo.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineJumpTableInfo.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/CodeGen/TargetRegisterInfo.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/GlobalVariable.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCExpr.h" 28 #include "llvm/Support/DivisionByConstantInfo.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/KnownBits.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include <cctype> 34 using namespace llvm; 35 36 /// NOTE: The TargetMachine owns TLOF. 37 TargetLowering::TargetLowering(const TargetMachine &tm) 38 : TargetLoweringBase(tm) {} 39 40 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 41 return nullptr; 42 } 43 44 bool TargetLowering::isPositionIndependent() const { 45 return getTargetMachine().isPositionIndependent(); 46 } 47 48 /// Check whether a given call node is in tail position within its function. If 49 /// so, it sets Chain to the input chain of the tail call. 50 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 51 SDValue &Chain) const { 52 const Function &F = DAG.getMachineFunction().getFunction(); 53 54 // First, check if tail calls have been disabled in this function. 55 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 56 return false; 57 58 // Conservatively require the attributes of the call to match those of 59 // the return. Ignore following attributes because they don't affect the 60 // call sequence. 61 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 62 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable, 63 Attribute::DereferenceableOrNull, Attribute::NoAlias, 64 Attribute::NonNull, Attribute::NoUndef}) 65 CallerAttrs.removeAttribute(Attr); 66 67 if (CallerAttrs.hasAttributes()) 68 return false; 69 70 // It's not safe to eliminate the sign / zero extension of the return value. 71 if (CallerAttrs.contains(Attribute::ZExt) || 72 CallerAttrs.contains(Attribute::SExt)) 73 return false; 74 75 // Check if the only use is a function return node. 76 return isUsedByReturnOnly(Node, Chain); 77 } 78 79 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 80 const uint32_t *CallerPreservedMask, 81 const SmallVectorImpl<CCValAssign> &ArgLocs, 82 const SmallVectorImpl<SDValue> &OutVals) const { 83 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 84 const CCValAssign &ArgLoc = ArgLocs[I]; 85 if (!ArgLoc.isRegLoc()) 86 continue; 87 MCRegister Reg = ArgLoc.getLocReg(); 88 // Only look at callee saved registers. 89 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 90 continue; 91 // Check that we pass the value used for the caller. 92 // (We look for a CopyFromReg reading a virtual register that is used 93 // for the function live-in value of register Reg) 94 SDValue Value = OutVals[I]; 95 if (Value->getOpcode() != ISD::CopyFromReg) 96 return false; 97 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 98 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 99 return false; 100 } 101 return true; 102 } 103 104 /// Set CallLoweringInfo attribute flags based on a call instruction 105 /// and called function attributes. 106 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 107 unsigned ArgIdx) { 108 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 109 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 110 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 111 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 112 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 113 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 114 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 115 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 116 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 117 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 118 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 119 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 120 Alignment = Call->getParamStackAlign(ArgIdx); 121 IndirectType = nullptr; 122 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 123 "multiple ABI attributes?"); 124 if (IsByVal) { 125 IndirectType = Call->getParamByValType(ArgIdx); 126 if (!Alignment) 127 Alignment = Call->getParamAlign(ArgIdx); 128 } 129 if (IsPreallocated) 130 IndirectType = Call->getParamPreallocatedType(ArgIdx); 131 if (IsInAlloca) 132 IndirectType = Call->getParamInAllocaType(ArgIdx); 133 if (IsSRet) 134 IndirectType = Call->getParamStructRetType(ArgIdx); 135 } 136 137 /// Generate a libcall taking the given operands as arguments and returning a 138 /// result of type RetVT. 139 std::pair<SDValue, SDValue> 140 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 141 ArrayRef<SDValue> Ops, 142 MakeLibCallOptions CallOptions, 143 const SDLoc &dl, 144 SDValue InChain) const { 145 if (!InChain) 146 InChain = DAG.getEntryNode(); 147 148 TargetLowering::ArgListTy Args; 149 Args.reserve(Ops.size()); 150 151 TargetLowering::ArgListEntry Entry; 152 for (unsigned i = 0; i < Ops.size(); ++i) { 153 SDValue NewOp = Ops[i]; 154 Entry.Node = NewOp; 155 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 156 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 157 CallOptions.IsSExt); 158 Entry.IsZExt = !Entry.IsSExt; 159 160 if (CallOptions.IsSoften && 161 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 162 Entry.IsSExt = Entry.IsZExt = false; 163 } 164 Args.push_back(Entry); 165 } 166 167 if (LC == RTLIB::UNKNOWN_LIBCALL) 168 report_fatal_error("Unsupported library call operation!"); 169 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 170 getPointerTy(DAG.getDataLayout())); 171 172 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 173 TargetLowering::CallLoweringInfo CLI(DAG); 174 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 175 bool zeroExtend = !signExtend; 176 177 if (CallOptions.IsSoften && 178 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 179 signExtend = zeroExtend = false; 180 } 181 182 CLI.setDebugLoc(dl) 183 .setChain(InChain) 184 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 185 .setNoReturn(CallOptions.DoesNotReturn) 186 .setDiscardResult(!CallOptions.IsReturnValueUsed) 187 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 188 .setSExtResult(signExtend) 189 .setZExtResult(zeroExtend); 190 return LowerCallTo(CLI); 191 } 192 193 bool TargetLowering::findOptimalMemOpLowering( 194 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 195 unsigned SrcAS, const AttributeList &FuncAttributes) const { 196 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 197 return false; 198 199 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 200 201 if (VT == MVT::Other) { 202 // Use the largest integer type whose alignment constraints are satisfied. 203 // We only need to check DstAlign here as SrcAlign is always greater or 204 // equal to DstAlign (or zero). 205 VT = MVT::i64; 206 if (Op.isFixedDstAlign()) 207 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 208 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 209 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 210 assert(VT.isInteger()); 211 212 // Find the largest legal integer type. 213 MVT LVT = MVT::i64; 214 while (!isTypeLegal(LVT)) 215 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 216 assert(LVT.isInteger()); 217 218 // If the type we've chosen is larger than the largest legal integer type 219 // then use that instead. 220 if (VT.bitsGT(LVT)) 221 VT = LVT; 222 } 223 224 unsigned NumMemOps = 0; 225 uint64_t Size = Op.size(); 226 while (Size) { 227 unsigned VTSize = VT.getSizeInBits() / 8; 228 while (VTSize > Size) { 229 // For now, only use non-vector load / store's for the left-over pieces. 230 EVT NewVT = VT; 231 unsigned NewVTSize; 232 233 bool Found = false; 234 if (VT.isVector() || VT.isFloatingPoint()) { 235 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 236 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 237 isSafeMemOpType(NewVT.getSimpleVT())) 238 Found = true; 239 else if (NewVT == MVT::i64 && 240 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 241 isSafeMemOpType(MVT::f64)) { 242 // i64 is usually not legal on 32-bit targets, but f64 may be. 243 NewVT = MVT::f64; 244 Found = true; 245 } 246 } 247 248 if (!Found) { 249 do { 250 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 251 if (NewVT == MVT::i8) 252 break; 253 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 254 } 255 NewVTSize = NewVT.getSizeInBits() / 8; 256 257 // If the new VT cannot cover all of the remaining bits, then consider 258 // issuing a (or a pair of) unaligned and overlapping load / store. 259 bool Fast; 260 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 261 allowsMisalignedMemoryAccesses( 262 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 263 MachineMemOperand::MONone, &Fast) && 264 Fast) 265 VTSize = Size; 266 else { 267 VT = NewVT; 268 VTSize = NewVTSize; 269 } 270 } 271 272 if (++NumMemOps > Limit) 273 return false; 274 275 MemOps.push_back(VT); 276 Size -= VTSize; 277 } 278 279 return true; 280 } 281 282 /// Soften the operands of a comparison. This code is shared among BR_CC, 283 /// SELECT_CC, and SETCC handlers. 284 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 285 SDValue &NewLHS, SDValue &NewRHS, 286 ISD::CondCode &CCCode, 287 const SDLoc &dl, const SDValue OldLHS, 288 const SDValue OldRHS) const { 289 SDValue Chain; 290 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 291 OldRHS, Chain); 292 } 293 294 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 295 SDValue &NewLHS, SDValue &NewRHS, 296 ISD::CondCode &CCCode, 297 const SDLoc &dl, const SDValue OldLHS, 298 const SDValue OldRHS, 299 SDValue &Chain, 300 bool IsSignaling) const { 301 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 302 // not supporting it. We can update this code when libgcc provides such 303 // functions. 304 305 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 306 && "Unsupported setcc type!"); 307 308 // Expand into one or more soft-fp libcall(s). 309 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 310 bool ShouldInvertCC = false; 311 switch (CCCode) { 312 case ISD::SETEQ: 313 case ISD::SETOEQ: 314 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 315 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 316 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 317 break; 318 case ISD::SETNE: 319 case ISD::SETUNE: 320 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 321 (VT == MVT::f64) ? RTLIB::UNE_F64 : 322 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 323 break; 324 case ISD::SETGE: 325 case ISD::SETOGE: 326 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 327 (VT == MVT::f64) ? RTLIB::OGE_F64 : 328 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 329 break; 330 case ISD::SETLT: 331 case ISD::SETOLT: 332 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 333 (VT == MVT::f64) ? RTLIB::OLT_F64 : 334 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 335 break; 336 case ISD::SETLE: 337 case ISD::SETOLE: 338 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 339 (VT == MVT::f64) ? RTLIB::OLE_F64 : 340 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 341 break; 342 case ISD::SETGT: 343 case ISD::SETOGT: 344 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 345 (VT == MVT::f64) ? RTLIB::OGT_F64 : 346 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 347 break; 348 case ISD::SETO: 349 ShouldInvertCC = true; 350 LLVM_FALLTHROUGH; 351 case ISD::SETUO: 352 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 353 (VT == MVT::f64) ? RTLIB::UO_F64 : 354 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 355 break; 356 case ISD::SETONE: 357 // SETONE = O && UNE 358 ShouldInvertCC = true; 359 LLVM_FALLTHROUGH; 360 case ISD::SETUEQ: 361 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 362 (VT == MVT::f64) ? RTLIB::UO_F64 : 363 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 364 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 365 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 366 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 367 break; 368 default: 369 // Invert CC for unordered comparisons 370 ShouldInvertCC = true; 371 switch (CCCode) { 372 case ISD::SETULT: 373 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 374 (VT == MVT::f64) ? RTLIB::OGE_F64 : 375 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 376 break; 377 case ISD::SETULE: 378 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 379 (VT == MVT::f64) ? RTLIB::OGT_F64 : 380 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 381 break; 382 case ISD::SETUGT: 383 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 384 (VT == MVT::f64) ? RTLIB::OLE_F64 : 385 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 386 break; 387 case ISD::SETUGE: 388 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 389 (VT == MVT::f64) ? RTLIB::OLT_F64 : 390 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 391 break; 392 default: llvm_unreachable("Do not know how to soften this setcc!"); 393 } 394 } 395 396 // Use the target specific return value for comparions lib calls. 397 EVT RetVT = getCmpLibcallReturnType(); 398 SDValue Ops[2] = {NewLHS, NewRHS}; 399 TargetLowering::MakeLibCallOptions CallOptions; 400 EVT OpsVT[2] = { OldLHS.getValueType(), 401 OldRHS.getValueType() }; 402 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 403 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 404 NewLHS = Call.first; 405 NewRHS = DAG.getConstant(0, dl, RetVT); 406 407 CCCode = getCmpLibcallCC(LC1); 408 if (ShouldInvertCC) { 409 assert(RetVT.isInteger()); 410 CCCode = getSetCCInverse(CCCode, RetVT); 411 } 412 413 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 414 // Update Chain. 415 Chain = Call.second; 416 } else { 417 EVT SetCCVT = 418 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 419 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 420 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 421 CCCode = getCmpLibcallCC(LC2); 422 if (ShouldInvertCC) 423 CCCode = getSetCCInverse(CCCode, RetVT); 424 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 425 if (Chain) 426 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 427 Call2.second); 428 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 429 Tmp.getValueType(), Tmp, NewLHS); 430 NewRHS = SDValue(); 431 } 432 } 433 434 /// Return the entry encoding for a jump table in the current function. The 435 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 436 unsigned TargetLowering::getJumpTableEncoding() const { 437 // In non-pic modes, just use the address of a block. 438 if (!isPositionIndependent()) 439 return MachineJumpTableInfo::EK_BlockAddress; 440 441 // In PIC mode, if the target supports a GPRel32 directive, use it. 442 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 443 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 444 445 // Otherwise, use a label difference. 446 return MachineJumpTableInfo::EK_LabelDifference32; 447 } 448 449 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 450 SelectionDAG &DAG) const { 451 // If our PIC model is GP relative, use the global offset table as the base. 452 unsigned JTEncoding = getJumpTableEncoding(); 453 454 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 455 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 456 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 457 458 return Table; 459 } 460 461 /// This returns the relocation base for the given PIC jumptable, the same as 462 /// getPICJumpTableRelocBase, but as an MCExpr. 463 const MCExpr * 464 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 465 unsigned JTI,MCContext &Ctx) const{ 466 // The normal PIC reloc base is the label at the start of the jump table. 467 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 468 } 469 470 bool 471 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 472 const TargetMachine &TM = getTargetMachine(); 473 const GlobalValue *GV = GA->getGlobal(); 474 475 // If the address is not even local to this DSO we will have to load it from 476 // a got and then add the offset. 477 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 478 return false; 479 480 // If the code is position independent we will have to add a base register. 481 if (isPositionIndependent()) 482 return false; 483 484 // Otherwise we can do it. 485 return true; 486 } 487 488 //===----------------------------------------------------------------------===// 489 // Optimization Methods 490 //===----------------------------------------------------------------------===// 491 492 /// If the specified instruction has a constant integer operand and there are 493 /// bits set in that constant that are not demanded, then clear those bits and 494 /// return true. 495 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 496 const APInt &DemandedBits, 497 const APInt &DemandedElts, 498 TargetLoweringOpt &TLO) const { 499 SDLoc DL(Op); 500 unsigned Opcode = Op.getOpcode(); 501 502 // Do target-specific constant optimization. 503 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 504 return TLO.New.getNode(); 505 506 // FIXME: ISD::SELECT, ISD::SELECT_CC 507 switch (Opcode) { 508 default: 509 break; 510 case ISD::XOR: 511 case ISD::AND: 512 case ISD::OR: { 513 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 514 if (!Op1C || Op1C->isOpaque()) 515 return false; 516 517 // If this is a 'not' op, don't touch it because that's a canonical form. 518 const APInt &C = Op1C->getAPIntValue(); 519 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 520 return false; 521 522 if (!C.isSubsetOf(DemandedBits)) { 523 EVT VT = Op.getValueType(); 524 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 525 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 526 return TLO.CombineTo(Op, NewOp); 527 } 528 529 break; 530 } 531 } 532 533 return false; 534 } 535 536 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 537 const APInt &DemandedBits, 538 TargetLoweringOpt &TLO) const { 539 EVT VT = Op.getValueType(); 540 APInt DemandedElts = VT.isVector() 541 ? APInt::getAllOnes(VT.getVectorNumElements()) 542 : APInt(1, 1); 543 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 544 } 545 546 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 547 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 548 /// generalized for targets with other types of implicit widening casts. 549 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 550 const APInt &Demanded, 551 TargetLoweringOpt &TLO) const { 552 assert(Op.getNumOperands() == 2 && 553 "ShrinkDemandedOp only supports binary operators!"); 554 assert(Op.getNode()->getNumValues() == 1 && 555 "ShrinkDemandedOp only supports nodes with one result!"); 556 557 SelectionDAG &DAG = TLO.DAG; 558 SDLoc dl(Op); 559 560 // Early return, as this function cannot handle vector types. 561 if (Op.getValueType().isVector()) 562 return false; 563 564 // Don't do this if the node has another user, which may require the 565 // full value. 566 if (!Op.getNode()->hasOneUse()) 567 return false; 568 569 // Search for the smallest integer type with free casts to and from 570 // Op's type. For expedience, just check power-of-2 integer types. 571 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 572 unsigned DemandedSize = Demanded.getActiveBits(); 573 unsigned SmallVTBits = DemandedSize; 574 if (!isPowerOf2_32(SmallVTBits)) 575 SmallVTBits = NextPowerOf2(SmallVTBits); 576 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 577 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 578 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 579 TLI.isZExtFree(SmallVT, Op.getValueType())) { 580 // We found a type with free casts. 581 SDValue X = DAG.getNode( 582 Op.getOpcode(), dl, SmallVT, 583 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 584 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 585 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 586 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 587 return TLO.CombineTo(Op, Z); 588 } 589 } 590 return false; 591 } 592 593 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 594 DAGCombinerInfo &DCI) const { 595 SelectionDAG &DAG = DCI.DAG; 596 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 597 !DCI.isBeforeLegalizeOps()); 598 KnownBits Known; 599 600 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 601 if (Simplified) { 602 DCI.AddToWorklist(Op.getNode()); 603 DCI.CommitTargetLoweringOpt(TLO); 604 } 605 return Simplified; 606 } 607 608 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 609 const APInt &DemandedElts, 610 DAGCombinerInfo &DCI) const { 611 SelectionDAG &DAG = DCI.DAG; 612 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 613 !DCI.isBeforeLegalizeOps()); 614 KnownBits Known; 615 616 bool Simplified = 617 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 618 if (Simplified) { 619 DCI.AddToWorklist(Op.getNode()); 620 DCI.CommitTargetLoweringOpt(TLO); 621 } 622 return Simplified; 623 } 624 625 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 626 KnownBits &Known, 627 TargetLoweringOpt &TLO, 628 unsigned Depth, 629 bool AssumeSingleUse) const { 630 EVT VT = Op.getValueType(); 631 632 // TODO: We can probably do more work on calculating the known bits and 633 // simplifying the operations for scalable vectors, but for now we just 634 // bail out. 635 if (VT.isScalableVector()) { 636 // Pretend we don't know anything for now. 637 Known = KnownBits(DemandedBits.getBitWidth()); 638 return false; 639 } 640 641 APInt DemandedElts = VT.isVector() 642 ? APInt::getAllOnes(VT.getVectorNumElements()) 643 : APInt(1, 1); 644 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 645 AssumeSingleUse); 646 } 647 648 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 649 // TODO: Under what circumstances can we create nodes? Constant folding? 650 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 651 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 652 SelectionDAG &DAG, unsigned Depth) const { 653 // Limit search depth. 654 if (Depth >= SelectionDAG::MaxRecursionDepth) 655 return SDValue(); 656 657 // Ignore UNDEFs. 658 if (Op.isUndef()) 659 return SDValue(); 660 661 // Not demanding any bits/elts from Op. 662 if (DemandedBits == 0 || DemandedElts == 0) 663 return DAG.getUNDEF(Op.getValueType()); 664 665 bool IsLE = DAG.getDataLayout().isLittleEndian(); 666 unsigned NumElts = DemandedElts.getBitWidth(); 667 unsigned BitWidth = DemandedBits.getBitWidth(); 668 KnownBits LHSKnown, RHSKnown; 669 switch (Op.getOpcode()) { 670 case ISD::BITCAST: { 671 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 672 EVT SrcVT = Src.getValueType(); 673 EVT DstVT = Op.getValueType(); 674 if (SrcVT == DstVT) 675 return Src; 676 677 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 678 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 679 if (NumSrcEltBits == NumDstEltBits) 680 if (SDValue V = SimplifyMultipleUseDemandedBits( 681 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 682 return DAG.getBitcast(DstVT, V); 683 684 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 685 unsigned Scale = NumDstEltBits / NumSrcEltBits; 686 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 687 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 688 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 689 for (unsigned i = 0; i != Scale; ++i) { 690 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 691 unsigned BitOffset = EltOffset * NumSrcEltBits; 692 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 693 if (!Sub.isZero()) { 694 DemandedSrcBits |= Sub; 695 for (unsigned j = 0; j != NumElts; ++j) 696 if (DemandedElts[j]) 697 DemandedSrcElts.setBit((j * Scale) + i); 698 } 699 } 700 701 if (SDValue V = SimplifyMultipleUseDemandedBits( 702 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 703 return DAG.getBitcast(DstVT, V); 704 } 705 706 // TODO - bigendian once we have test coverage. 707 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 708 unsigned Scale = NumSrcEltBits / NumDstEltBits; 709 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 710 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 711 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 712 for (unsigned i = 0; i != NumElts; ++i) 713 if (DemandedElts[i]) { 714 unsigned Offset = (i % Scale) * NumDstEltBits; 715 DemandedSrcBits.insertBits(DemandedBits, Offset); 716 DemandedSrcElts.setBit(i / Scale); 717 } 718 719 if (SDValue V = SimplifyMultipleUseDemandedBits( 720 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 721 return DAG.getBitcast(DstVT, V); 722 } 723 724 break; 725 } 726 case ISD::AND: { 727 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 728 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 729 730 // If all of the demanded bits are known 1 on one side, return the other. 731 // These bits cannot contribute to the result of the 'and' in this 732 // context. 733 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 734 return Op.getOperand(0); 735 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 736 return Op.getOperand(1); 737 break; 738 } 739 case ISD::OR: { 740 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 741 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 742 743 // If all of the demanded bits are known zero on one side, return the 744 // other. These bits cannot contribute to the result of the 'or' in this 745 // context. 746 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 747 return Op.getOperand(0); 748 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 749 return Op.getOperand(1); 750 break; 751 } 752 case ISD::XOR: { 753 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 754 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 755 756 // If all of the demanded bits are known zero on one side, return the 757 // other. 758 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 759 return Op.getOperand(0); 760 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 761 return Op.getOperand(1); 762 break; 763 } 764 case ISD::SHL: { 765 // If we are only demanding sign bits then we can use the shift source 766 // directly. 767 if (const APInt *MaxSA = 768 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 769 SDValue Op0 = Op.getOperand(0); 770 unsigned ShAmt = MaxSA->getZExtValue(); 771 unsigned NumSignBits = 772 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 773 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 774 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 775 return Op0; 776 } 777 break; 778 } 779 case ISD::SETCC: { 780 SDValue Op0 = Op.getOperand(0); 781 SDValue Op1 = Op.getOperand(1); 782 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 783 // If (1) we only need the sign-bit, (2) the setcc operands are the same 784 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 785 // -1, we may be able to bypass the setcc. 786 if (DemandedBits.isSignMask() && 787 Op0.getScalarValueSizeInBits() == BitWidth && 788 getBooleanContents(Op0.getValueType()) == 789 BooleanContent::ZeroOrNegativeOneBooleanContent) { 790 // If we're testing X < 0, then this compare isn't needed - just use X! 791 // FIXME: We're limiting to integer types here, but this should also work 792 // if we don't care about FP signed-zero. The use of SETLT with FP means 793 // that we don't care about NaNs. 794 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 795 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 796 return Op0; 797 } 798 break; 799 } 800 case ISD::SIGN_EXTEND_INREG: { 801 // If none of the extended bits are demanded, eliminate the sextinreg. 802 SDValue Op0 = Op.getOperand(0); 803 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 804 unsigned ExBits = ExVT.getScalarSizeInBits(); 805 if (DemandedBits.getActiveBits() <= ExBits) 806 return Op0; 807 // If the input is already sign extended, just drop the extension. 808 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 809 if (NumSignBits >= (BitWidth - ExBits + 1)) 810 return Op0; 811 break; 812 } 813 case ISD::ANY_EXTEND_VECTOR_INREG: 814 case ISD::SIGN_EXTEND_VECTOR_INREG: 815 case ISD::ZERO_EXTEND_VECTOR_INREG: { 816 // If we only want the lowest element and none of extended bits, then we can 817 // return the bitcasted source vector. 818 SDValue Src = Op.getOperand(0); 819 EVT SrcVT = Src.getValueType(); 820 EVT DstVT = Op.getValueType(); 821 if (IsLE && DemandedElts == 1 && 822 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 823 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 824 return DAG.getBitcast(DstVT, Src); 825 } 826 break; 827 } 828 case ISD::INSERT_VECTOR_ELT: { 829 // If we don't demand the inserted element, return the base vector. 830 SDValue Vec = Op.getOperand(0); 831 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 832 EVT VecVT = Vec.getValueType(); 833 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 834 !DemandedElts[CIdx->getZExtValue()]) 835 return Vec; 836 break; 837 } 838 case ISD::INSERT_SUBVECTOR: { 839 SDValue Vec = Op.getOperand(0); 840 SDValue Sub = Op.getOperand(1); 841 uint64_t Idx = Op.getConstantOperandVal(2); 842 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 843 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 844 // If we don't demand the inserted subvector, return the base vector. 845 if (DemandedSubElts == 0) 846 return Vec; 847 // If this simply widens the lowest subvector, see if we can do it earlier. 848 if (Idx == 0 && Vec.isUndef()) { 849 if (SDValue NewSub = SimplifyMultipleUseDemandedBits( 850 Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1)) 851 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 852 Op.getOperand(0), NewSub, Op.getOperand(2)); 853 } 854 break; 855 } 856 case ISD::VECTOR_SHUFFLE: { 857 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 858 859 // If all the demanded elts are from one operand and are inline, 860 // then we can use the operand directly. 861 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 862 for (unsigned i = 0; i != NumElts; ++i) { 863 int M = ShuffleMask[i]; 864 if (M < 0 || !DemandedElts[i]) 865 continue; 866 AllUndef = false; 867 IdentityLHS &= (M == (int)i); 868 IdentityRHS &= ((M - NumElts) == i); 869 } 870 871 if (AllUndef) 872 return DAG.getUNDEF(Op.getValueType()); 873 if (IdentityLHS) 874 return Op.getOperand(0); 875 if (IdentityRHS) 876 return Op.getOperand(1); 877 break; 878 } 879 default: 880 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 881 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 882 Op, DemandedBits, DemandedElts, DAG, Depth)) 883 return V; 884 break; 885 } 886 return SDValue(); 887 } 888 889 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 890 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 891 unsigned Depth) const { 892 EVT VT = Op.getValueType(); 893 APInt DemandedElts = VT.isVector() 894 ? APInt::getAllOnes(VT.getVectorNumElements()) 895 : APInt(1, 1); 896 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 897 Depth); 898 } 899 900 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 901 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 902 unsigned Depth) const { 903 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 904 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 905 Depth); 906 } 907 908 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 909 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 910 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG, 911 const TargetLowering &TLI, 912 const APInt &DemandedBits, 913 const APInt &DemandedElts, 914 unsigned Depth) { 915 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 916 "SRL or SRA node is required here!"); 917 // Is the right shift using an immediate value of 1? 918 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 919 if (!N1C || !N1C->isOne()) 920 return SDValue(); 921 922 // We are looking for an avgfloor 923 // add(ext, ext) 924 // or one of these as a avgceil 925 // add(add(ext, ext), 1) 926 // add(add(ext, 1), ext) 927 // add(ext, add(ext, 1)) 928 SDValue Add = Op.getOperand(0); 929 if (Add.getOpcode() != ISD::ADD) 930 return SDValue(); 931 932 SDValue ExtOpA = Add.getOperand(0); 933 SDValue ExtOpB = Add.getOperand(1); 934 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) { 935 ConstantSDNode *ConstOp; 936 if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) && 937 ConstOp->isOne()) { 938 ExtOpA = Op2; 939 ExtOpB = Op3; 940 return true; 941 } 942 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 943 ConstOp->isOne()) { 944 ExtOpA = Op1; 945 ExtOpB = Op3; 946 return true; 947 } 948 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 949 ConstOp->isOne()) { 950 ExtOpA = Op1; 951 ExtOpB = Op2; 952 return true; 953 } 954 return false; 955 }; 956 bool IsCeil = 957 (ExtOpA.getOpcode() == ISD::ADD && 958 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) || 959 (ExtOpB.getOpcode() == ISD::ADD && 960 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA)); 961 962 // If the shift is signed (sra): 963 // - Needs >= 2 sign bit for both operands. 964 // - Needs >= 2 zero bits. 965 // If the shift is unsigned (srl): 966 // - Needs >= 1 zero bit for both operands. 967 // - Needs 1 demanded bit zero and >= 2 sign bits. 968 unsigned ShiftOpc = Op.getOpcode(); 969 bool IsSigned = false; 970 unsigned KnownBits; 971 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 972 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 973 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 974 unsigned NumZeroA = 975 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 976 unsigned NumZeroB = 977 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 978 unsigned NumZero = std::min(NumZeroA, NumZeroB); 979 980 switch (ShiftOpc) { 981 default: 982 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 983 case ISD::SRA: { 984 if (NumZero >= 2 && NumSigned < NumZero) { 985 IsSigned = false; 986 KnownBits = NumZero; 987 break; 988 } 989 if (NumSigned >= 1) { 990 IsSigned = true; 991 KnownBits = NumSigned; 992 break; 993 } 994 return SDValue(); 995 } 996 case ISD::SRL: { 997 if (NumZero >= 1 && NumSigned < NumZero) { 998 IsSigned = false; 999 KnownBits = NumZero; 1000 break; 1001 } 1002 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1003 IsSigned = true; 1004 KnownBits = NumSigned; 1005 break; 1006 } 1007 return SDValue(); 1008 } 1009 } 1010 1011 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1012 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1013 1014 // Find the smallest power-2 type that is legal for this vector size and 1015 // operation, given the original type size and the number of known sign/zero 1016 // bits. 1017 EVT VT = Op.getValueType(); 1018 unsigned MinWidth = 1019 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1020 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth)); 1021 if (VT.isVector()) 1022 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1023 if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) 1024 return SDValue(); 1025 1026 SDLoc DL(Op); 1027 SDValue ResultAVG = 1028 DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA), 1029 DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB)); 1030 return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT, 1031 ResultAVG); 1032 } 1033 1034 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1035 /// result of Op are ever used downstream. If we can use this information to 1036 /// simplify Op, create a new simplified DAG node and return true, returning the 1037 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1038 /// return a mask of Known bits for the expression (used to simplify the 1039 /// caller). The Known bits may only be accurate for those bits in the 1040 /// OriginalDemandedBits and OriginalDemandedElts. 1041 bool TargetLowering::SimplifyDemandedBits( 1042 SDValue Op, const APInt &OriginalDemandedBits, 1043 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1044 unsigned Depth, bool AssumeSingleUse) const { 1045 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1046 assert(Op.getScalarValueSizeInBits() == BitWidth && 1047 "Mask size mismatches value type size!"); 1048 1049 // Don't know anything. 1050 Known = KnownBits(BitWidth); 1051 1052 // TODO: We can probably do more work on calculating the known bits and 1053 // simplifying the operations for scalable vectors, but for now we just 1054 // bail out. 1055 if (Op.getValueType().isScalableVector()) 1056 return false; 1057 1058 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1059 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1060 assert((!Op.getValueType().isVector() || 1061 NumElts == Op.getValueType().getVectorNumElements()) && 1062 "Unexpected vector size"); 1063 1064 APInt DemandedBits = OriginalDemandedBits; 1065 APInt DemandedElts = OriginalDemandedElts; 1066 SDLoc dl(Op); 1067 auto &DL = TLO.DAG.getDataLayout(); 1068 1069 // Undef operand. 1070 if (Op.isUndef()) 1071 return false; 1072 1073 if (Op.getOpcode() == ISD::Constant) { 1074 // We know all of the bits for a constant! 1075 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 1076 return false; 1077 } 1078 1079 if (Op.getOpcode() == ISD::ConstantFP) { 1080 // We know all of the bits for a floating point constant! 1081 Known = KnownBits::makeConstant( 1082 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1083 return false; 1084 } 1085 1086 // Other users may use these bits. 1087 EVT VT = Op.getValueType(); 1088 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 1089 if (Depth != 0) { 1090 // If not at the root, Just compute the Known bits to 1091 // simplify things downstream. 1092 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1093 return false; 1094 } 1095 // If this is the root being simplified, allow it to have multiple uses, 1096 // just set the DemandedBits/Elts to all bits. 1097 DemandedBits = APInt::getAllOnes(BitWidth); 1098 DemandedElts = APInt::getAllOnes(NumElts); 1099 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1100 // Not demanding any bits/elts from Op. 1101 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1102 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1103 // Limit search depth. 1104 return false; 1105 } 1106 1107 KnownBits Known2; 1108 switch (Op.getOpcode()) { 1109 case ISD::TargetConstant: 1110 llvm_unreachable("Can't simplify this node"); 1111 case ISD::SCALAR_TO_VECTOR: { 1112 if (!DemandedElts[0]) 1113 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1114 1115 KnownBits SrcKnown; 1116 SDValue Src = Op.getOperand(0); 1117 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1118 APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth); 1119 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1120 return true; 1121 1122 // Upper elements are undef, so only get the knownbits if we just demand 1123 // the bottom element. 1124 if (DemandedElts == 1) 1125 Known = SrcKnown.anyextOrTrunc(BitWidth); 1126 break; 1127 } 1128 case ISD::BUILD_VECTOR: 1129 // Collect the known bits that are shared by every demanded element. 1130 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1131 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1132 return false; // Don't fall through, will infinitely loop. 1133 case ISD::LOAD: { 1134 auto *LD = cast<LoadSDNode>(Op); 1135 if (getTargetConstantFromLoad(LD)) { 1136 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1137 return false; // Don't fall through, will infinitely loop. 1138 } 1139 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1140 // If this is a ZEXTLoad and we are looking at the loaded value. 1141 EVT MemVT = LD->getMemoryVT(); 1142 unsigned MemBits = MemVT.getScalarSizeInBits(); 1143 Known.Zero.setBitsFrom(MemBits); 1144 return false; // Don't fall through, will infinitely loop. 1145 } 1146 break; 1147 } 1148 case ISD::INSERT_VECTOR_ELT: { 1149 SDValue Vec = Op.getOperand(0); 1150 SDValue Scl = Op.getOperand(1); 1151 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1152 EVT VecVT = Vec.getValueType(); 1153 1154 // If index isn't constant, assume we need all vector elements AND the 1155 // inserted element. 1156 APInt DemandedVecElts(DemandedElts); 1157 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1158 unsigned Idx = CIdx->getZExtValue(); 1159 DemandedVecElts.clearBit(Idx); 1160 1161 // Inserted element is not required. 1162 if (!DemandedElts[Idx]) 1163 return TLO.CombineTo(Op, Vec); 1164 } 1165 1166 KnownBits KnownScl; 1167 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1168 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1169 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1170 return true; 1171 1172 Known = KnownScl.anyextOrTrunc(BitWidth); 1173 1174 KnownBits KnownVec; 1175 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1176 Depth + 1)) 1177 return true; 1178 1179 if (!!DemandedVecElts) 1180 Known = KnownBits::commonBits(Known, KnownVec); 1181 1182 return false; 1183 } 1184 case ISD::INSERT_SUBVECTOR: { 1185 // Demand any elements from the subvector and the remainder from the src its 1186 // inserted into. 1187 SDValue Src = Op.getOperand(0); 1188 SDValue Sub = Op.getOperand(1); 1189 uint64_t Idx = Op.getConstantOperandVal(2); 1190 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1191 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1192 APInt DemandedSrcElts = DemandedElts; 1193 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1194 1195 KnownBits KnownSub, KnownSrc; 1196 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1197 Depth + 1)) 1198 return true; 1199 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1200 Depth + 1)) 1201 return true; 1202 1203 Known.Zero.setAllBits(); 1204 Known.One.setAllBits(); 1205 if (!!DemandedSubElts) 1206 Known = KnownBits::commonBits(Known, KnownSub); 1207 if (!!DemandedSrcElts) 1208 Known = KnownBits::commonBits(Known, KnownSrc); 1209 1210 // Attempt to avoid multi-use src if we don't need anything from it. 1211 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1212 !DemandedSrcElts.isAllOnes()) { 1213 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1214 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1215 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1216 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1217 if (NewSub || NewSrc) { 1218 NewSub = NewSub ? NewSub : Sub; 1219 NewSrc = NewSrc ? NewSrc : Src; 1220 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1221 Op.getOperand(2)); 1222 return TLO.CombineTo(Op, NewOp); 1223 } 1224 } 1225 break; 1226 } 1227 case ISD::EXTRACT_SUBVECTOR: { 1228 // Offset the demanded elts by the subvector index. 1229 SDValue Src = Op.getOperand(0); 1230 if (Src.getValueType().isScalableVector()) 1231 break; 1232 uint64_t Idx = Op.getConstantOperandVal(1); 1233 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1234 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1235 1236 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1237 Depth + 1)) 1238 return true; 1239 1240 // Attempt to avoid multi-use src if we don't need anything from it. 1241 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1242 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1243 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1244 if (DemandedSrc) { 1245 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1246 Op.getOperand(1)); 1247 return TLO.CombineTo(Op, NewOp); 1248 } 1249 } 1250 break; 1251 } 1252 case ISD::CONCAT_VECTORS: { 1253 Known.Zero.setAllBits(); 1254 Known.One.setAllBits(); 1255 EVT SubVT = Op.getOperand(0).getValueType(); 1256 unsigned NumSubVecs = Op.getNumOperands(); 1257 unsigned NumSubElts = SubVT.getVectorNumElements(); 1258 for (unsigned i = 0; i != NumSubVecs; ++i) { 1259 APInt DemandedSubElts = 1260 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1261 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1262 Known2, TLO, Depth + 1)) 1263 return true; 1264 // Known bits are shared by every demanded subvector element. 1265 if (!!DemandedSubElts) 1266 Known = KnownBits::commonBits(Known, Known2); 1267 } 1268 break; 1269 } 1270 case ISD::VECTOR_SHUFFLE: { 1271 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1272 1273 // Collect demanded elements from shuffle operands.. 1274 APInt DemandedLHS(NumElts, 0); 1275 APInt DemandedRHS(NumElts, 0); 1276 for (unsigned i = 0; i != NumElts; ++i) { 1277 if (!DemandedElts[i]) 1278 continue; 1279 int M = ShuffleMask[i]; 1280 if (M < 0) { 1281 // For UNDEF elements, we don't know anything about the common state of 1282 // the shuffle result. 1283 DemandedLHS.clearAllBits(); 1284 DemandedRHS.clearAllBits(); 1285 break; 1286 } 1287 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1288 if (M < (int)NumElts) 1289 DemandedLHS.setBit(M); 1290 else 1291 DemandedRHS.setBit(M - NumElts); 1292 } 1293 1294 if (!!DemandedLHS || !!DemandedRHS) { 1295 SDValue Op0 = Op.getOperand(0); 1296 SDValue Op1 = Op.getOperand(1); 1297 1298 Known.Zero.setAllBits(); 1299 Known.One.setAllBits(); 1300 if (!!DemandedLHS) { 1301 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1302 Depth + 1)) 1303 return true; 1304 Known = KnownBits::commonBits(Known, Known2); 1305 } 1306 if (!!DemandedRHS) { 1307 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1308 Depth + 1)) 1309 return true; 1310 Known = KnownBits::commonBits(Known, Known2); 1311 } 1312 1313 // Attempt to avoid multi-use ops if we don't need anything from them. 1314 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1315 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1316 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1317 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1318 if (DemandedOp0 || DemandedOp1) { 1319 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1320 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1321 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1322 return TLO.CombineTo(Op, NewOp); 1323 } 1324 } 1325 break; 1326 } 1327 case ISD::AND: { 1328 SDValue Op0 = Op.getOperand(0); 1329 SDValue Op1 = Op.getOperand(1); 1330 1331 // If the RHS is a constant, check to see if the LHS would be zero without 1332 // using the bits from the RHS. Below, we use knowledge about the RHS to 1333 // simplify the LHS, here we're using information from the LHS to simplify 1334 // the RHS. 1335 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1336 // Do not increment Depth here; that can cause an infinite loop. 1337 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1338 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1339 if ((LHSKnown.Zero & DemandedBits) == 1340 (~RHSC->getAPIntValue() & DemandedBits)) 1341 return TLO.CombineTo(Op, Op0); 1342 1343 // If any of the set bits in the RHS are known zero on the LHS, shrink 1344 // the constant. 1345 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1346 DemandedElts, TLO)) 1347 return true; 1348 1349 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1350 // constant, but if this 'and' is only clearing bits that were just set by 1351 // the xor, then this 'and' can be eliminated by shrinking the mask of 1352 // the xor. For example, for a 32-bit X: 1353 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1354 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1355 LHSKnown.One == ~RHSC->getAPIntValue()) { 1356 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1357 return TLO.CombineTo(Op, Xor); 1358 } 1359 } 1360 1361 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1362 Depth + 1)) 1363 return true; 1364 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1365 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1366 Known2, TLO, Depth + 1)) 1367 return true; 1368 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1369 1370 // Attempt to avoid multi-use ops if we don't need anything from them. 1371 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1372 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1373 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1374 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1375 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1376 if (DemandedOp0 || DemandedOp1) { 1377 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1378 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1379 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1380 return TLO.CombineTo(Op, NewOp); 1381 } 1382 } 1383 1384 // If all of the demanded bits are known one on one side, return the other. 1385 // These bits cannot contribute to the result of the 'and'. 1386 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1387 return TLO.CombineTo(Op, Op0); 1388 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1389 return TLO.CombineTo(Op, Op1); 1390 // If all of the demanded bits in the inputs are known zeros, return zero. 1391 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1392 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1393 // If the RHS is a constant, see if we can simplify it. 1394 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1395 TLO)) 1396 return true; 1397 // If the operation can be done in a smaller type, do so. 1398 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1399 return true; 1400 1401 Known &= Known2; 1402 break; 1403 } 1404 case ISD::OR: { 1405 SDValue Op0 = Op.getOperand(0); 1406 SDValue Op1 = Op.getOperand(1); 1407 1408 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1409 Depth + 1)) 1410 return true; 1411 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1412 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1413 Known2, TLO, Depth + 1)) 1414 return true; 1415 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1416 1417 // Attempt to avoid multi-use ops if we don't need anything from them. 1418 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1419 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1420 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1421 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1422 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1423 if (DemandedOp0 || DemandedOp1) { 1424 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1425 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1426 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1427 return TLO.CombineTo(Op, NewOp); 1428 } 1429 } 1430 1431 // If all of the demanded bits are known zero on one side, return the other. 1432 // These bits cannot contribute to the result of the 'or'. 1433 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1434 return TLO.CombineTo(Op, Op0); 1435 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1436 return TLO.CombineTo(Op, Op1); 1437 // If the RHS is a constant, see if we can simplify it. 1438 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1439 return true; 1440 // If the operation can be done in a smaller type, do so. 1441 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1442 return true; 1443 1444 Known |= Known2; 1445 break; 1446 } 1447 case ISD::XOR: { 1448 SDValue Op0 = Op.getOperand(0); 1449 SDValue Op1 = Op.getOperand(1); 1450 1451 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1452 Depth + 1)) 1453 return true; 1454 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1455 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1456 Depth + 1)) 1457 return true; 1458 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1459 1460 // Attempt to avoid multi-use ops if we don't need anything from them. 1461 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1462 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1463 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1464 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1465 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1466 if (DemandedOp0 || DemandedOp1) { 1467 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1468 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1469 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1470 return TLO.CombineTo(Op, NewOp); 1471 } 1472 } 1473 1474 // If all of the demanded bits are known zero on one side, return the other. 1475 // These bits cannot contribute to the result of the 'xor'. 1476 if (DemandedBits.isSubsetOf(Known.Zero)) 1477 return TLO.CombineTo(Op, Op0); 1478 if (DemandedBits.isSubsetOf(Known2.Zero)) 1479 return TLO.CombineTo(Op, Op1); 1480 // If the operation can be done in a smaller type, do so. 1481 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1482 return true; 1483 1484 // If all of the unknown bits are known to be zero on one side or the other 1485 // turn this into an *inclusive* or. 1486 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1487 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1488 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1489 1490 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1491 if (C) { 1492 // If one side is a constant, and all of the set bits in the constant are 1493 // also known set on the other side, turn this into an AND, as we know 1494 // the bits will be cleared. 1495 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1496 // NB: it is okay if more bits are known than are requested 1497 if (C->getAPIntValue() == Known2.One) { 1498 SDValue ANDC = 1499 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1500 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1501 } 1502 1503 // If the RHS is a constant, see if we can change it. Don't alter a -1 1504 // constant because that's a 'not' op, and that is better for combining 1505 // and codegen. 1506 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1507 // We're flipping all demanded bits. Flip the undemanded bits too. 1508 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1509 return TLO.CombineTo(Op, New); 1510 } 1511 } 1512 1513 // If we can't turn this into a 'not', try to shrink the constant. 1514 if (!C || !C->isAllOnes()) 1515 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1516 return true; 1517 1518 Known ^= Known2; 1519 break; 1520 } 1521 case ISD::SELECT: 1522 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1523 Depth + 1)) 1524 return true; 1525 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1526 Depth + 1)) 1527 return true; 1528 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1529 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1530 1531 // If the operands are constants, see if we can simplify them. 1532 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1533 return true; 1534 1535 // Only known if known in both the LHS and RHS. 1536 Known = KnownBits::commonBits(Known, Known2); 1537 break; 1538 case ISD::SELECT_CC: 1539 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1540 Depth + 1)) 1541 return true; 1542 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1543 Depth + 1)) 1544 return true; 1545 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1546 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1547 1548 // If the operands are constants, see if we can simplify them. 1549 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1550 return true; 1551 1552 // Only known if known in both the LHS and RHS. 1553 Known = KnownBits::commonBits(Known, Known2); 1554 break; 1555 case ISD::SETCC: { 1556 SDValue Op0 = Op.getOperand(0); 1557 SDValue Op1 = Op.getOperand(1); 1558 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1559 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1560 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1561 // -1, we may be able to bypass the setcc. 1562 if (DemandedBits.isSignMask() && 1563 Op0.getScalarValueSizeInBits() == BitWidth && 1564 getBooleanContents(Op0.getValueType()) == 1565 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1566 // If we're testing X < 0, then this compare isn't needed - just use X! 1567 // FIXME: We're limiting to integer types here, but this should also work 1568 // if we don't care about FP signed-zero. The use of SETLT with FP means 1569 // that we don't care about NaNs. 1570 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1571 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1572 return TLO.CombineTo(Op, Op0); 1573 1574 // TODO: Should we check for other forms of sign-bit comparisons? 1575 // Examples: X <= -1, X >= 0 1576 } 1577 if (getBooleanContents(Op0.getValueType()) == 1578 TargetLowering::ZeroOrOneBooleanContent && 1579 BitWidth > 1) 1580 Known.Zero.setBitsFrom(1); 1581 break; 1582 } 1583 case ISD::SHL: { 1584 SDValue Op0 = Op.getOperand(0); 1585 SDValue Op1 = Op.getOperand(1); 1586 EVT ShiftVT = Op1.getValueType(); 1587 1588 if (const APInt *SA = 1589 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1590 unsigned ShAmt = SA->getZExtValue(); 1591 if (ShAmt == 0) 1592 return TLO.CombineTo(Op, Op0); 1593 1594 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1595 // single shift. We can do this if the bottom bits (which are shifted 1596 // out) are never demanded. 1597 // TODO - support non-uniform vector amounts. 1598 if (Op0.getOpcode() == ISD::SRL) { 1599 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1600 if (const APInt *SA2 = 1601 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1602 unsigned C1 = SA2->getZExtValue(); 1603 unsigned Opc = ISD::SHL; 1604 int Diff = ShAmt - C1; 1605 if (Diff < 0) { 1606 Diff = -Diff; 1607 Opc = ISD::SRL; 1608 } 1609 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1610 return TLO.CombineTo( 1611 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1612 } 1613 } 1614 } 1615 1616 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1617 // are not demanded. This will likely allow the anyext to be folded away. 1618 // TODO - support non-uniform vector amounts. 1619 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1620 SDValue InnerOp = Op0.getOperand(0); 1621 EVT InnerVT = InnerOp.getValueType(); 1622 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1623 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1624 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1625 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1626 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1627 ShTy = InnerVT; 1628 SDValue NarrowShl = 1629 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1630 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1631 return TLO.CombineTo( 1632 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1633 } 1634 1635 // Repeat the SHL optimization above in cases where an extension 1636 // intervenes: (shl (anyext (shr x, c1)), c2) to 1637 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1638 // aren't demanded (as above) and that the shifted upper c1 bits of 1639 // x aren't demanded. 1640 // TODO - support non-uniform vector amounts. 1641 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1642 InnerOp.hasOneUse()) { 1643 if (const APInt *SA2 = 1644 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1645 unsigned InnerShAmt = SA2->getZExtValue(); 1646 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1647 DemandedBits.getActiveBits() <= 1648 (InnerBits - InnerShAmt + ShAmt) && 1649 DemandedBits.countTrailingZeros() >= ShAmt) { 1650 SDValue NewSA = 1651 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1652 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1653 InnerOp.getOperand(0)); 1654 return TLO.CombineTo( 1655 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1656 } 1657 } 1658 } 1659 } 1660 1661 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1662 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1663 Depth + 1)) 1664 return true; 1665 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1666 Known.Zero <<= ShAmt; 1667 Known.One <<= ShAmt; 1668 // low bits known zero. 1669 Known.Zero.setLowBits(ShAmt); 1670 1671 // Try shrinking the operation as long as the shift amount will still be 1672 // in range. 1673 if ((ShAmt < DemandedBits.getActiveBits()) && 1674 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1675 return true; 1676 } 1677 1678 // If we are only demanding sign bits then we can use the shift source 1679 // directly. 1680 if (const APInt *MaxSA = 1681 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1682 unsigned ShAmt = MaxSA->getZExtValue(); 1683 unsigned NumSignBits = 1684 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1685 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1686 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1687 return TLO.CombineTo(Op, Op0); 1688 } 1689 break; 1690 } 1691 case ISD::SRL: { 1692 SDValue Op0 = Op.getOperand(0); 1693 SDValue Op1 = Op.getOperand(1); 1694 EVT ShiftVT = Op1.getValueType(); 1695 1696 // Try to match AVG patterns. 1697 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1698 DemandedElts, Depth + 1)) 1699 return TLO.CombineTo(Op, AVG); 1700 1701 if (const APInt *SA = 1702 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1703 unsigned ShAmt = SA->getZExtValue(); 1704 if (ShAmt == 0) 1705 return TLO.CombineTo(Op, Op0); 1706 1707 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1708 // single shift. We can do this if the top bits (which are shifted out) 1709 // are never demanded. 1710 // TODO - support non-uniform vector amounts. 1711 if (Op0.getOpcode() == ISD::SHL) { 1712 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1713 if (const APInt *SA2 = 1714 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1715 unsigned C1 = SA2->getZExtValue(); 1716 unsigned Opc = ISD::SRL; 1717 int Diff = ShAmt - C1; 1718 if (Diff < 0) { 1719 Diff = -Diff; 1720 Opc = ISD::SHL; 1721 } 1722 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1723 return TLO.CombineTo( 1724 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1725 } 1726 } 1727 } 1728 1729 APInt InDemandedMask = (DemandedBits << ShAmt); 1730 1731 // If the shift is exact, then it does demand the low bits (and knows that 1732 // they are zero). 1733 if (Op->getFlags().hasExact()) 1734 InDemandedMask.setLowBits(ShAmt); 1735 1736 // Compute the new bits that are at the top now. 1737 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1738 Depth + 1)) 1739 return true; 1740 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1741 Known.Zero.lshrInPlace(ShAmt); 1742 Known.One.lshrInPlace(ShAmt); 1743 // High bits known zero. 1744 Known.Zero.setHighBits(ShAmt); 1745 } 1746 break; 1747 } 1748 case ISD::SRA: { 1749 SDValue Op0 = Op.getOperand(0); 1750 SDValue Op1 = Op.getOperand(1); 1751 EVT ShiftVT = Op1.getValueType(); 1752 1753 // If we only want bits that already match the signbit then we don't need 1754 // to shift. 1755 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1756 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1757 NumHiDemandedBits) 1758 return TLO.CombineTo(Op, Op0); 1759 1760 // If this is an arithmetic shift right and only the low-bit is set, we can 1761 // always convert this into a logical shr, even if the shift amount is 1762 // variable. The low bit of the shift cannot be an input sign bit unless 1763 // the shift amount is >= the size of the datatype, which is undefined. 1764 if (DemandedBits.isOne()) 1765 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1766 1767 // Try to match AVG patterns. 1768 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1769 DemandedElts, Depth + 1)) 1770 return TLO.CombineTo(Op, AVG); 1771 1772 if (const APInt *SA = 1773 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1774 unsigned ShAmt = SA->getZExtValue(); 1775 if (ShAmt == 0) 1776 return TLO.CombineTo(Op, Op0); 1777 1778 APInt InDemandedMask = (DemandedBits << ShAmt); 1779 1780 // If the shift is exact, then it does demand the low bits (and knows that 1781 // they are zero). 1782 if (Op->getFlags().hasExact()) 1783 InDemandedMask.setLowBits(ShAmt); 1784 1785 // If any of the demanded bits are produced by the sign extension, we also 1786 // demand the input sign bit. 1787 if (DemandedBits.countLeadingZeros() < ShAmt) 1788 InDemandedMask.setSignBit(); 1789 1790 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1791 Depth + 1)) 1792 return true; 1793 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1794 Known.Zero.lshrInPlace(ShAmt); 1795 Known.One.lshrInPlace(ShAmt); 1796 1797 // If the input sign bit is known to be zero, or if none of the top bits 1798 // are demanded, turn this into an unsigned shift right. 1799 if (Known.Zero[BitWidth - ShAmt - 1] || 1800 DemandedBits.countLeadingZeros() >= ShAmt) { 1801 SDNodeFlags Flags; 1802 Flags.setExact(Op->getFlags().hasExact()); 1803 return TLO.CombineTo( 1804 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1805 } 1806 1807 int Log2 = DemandedBits.exactLogBase2(); 1808 if (Log2 >= 0) { 1809 // The bit must come from the sign. 1810 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1811 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1812 } 1813 1814 if (Known.One[BitWidth - ShAmt - 1]) 1815 // New bits are known one. 1816 Known.One.setHighBits(ShAmt); 1817 1818 // Attempt to avoid multi-use ops if we don't need anything from them. 1819 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1820 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1821 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1822 if (DemandedOp0) { 1823 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1824 return TLO.CombineTo(Op, NewOp); 1825 } 1826 } 1827 } 1828 break; 1829 } 1830 case ISD::FSHL: 1831 case ISD::FSHR: { 1832 SDValue Op0 = Op.getOperand(0); 1833 SDValue Op1 = Op.getOperand(1); 1834 SDValue Op2 = Op.getOperand(2); 1835 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1836 1837 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1838 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1839 1840 // For fshl, 0-shift returns the 1st arg. 1841 // For fshr, 0-shift returns the 2nd arg. 1842 if (Amt == 0) { 1843 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1844 Known, TLO, Depth + 1)) 1845 return true; 1846 break; 1847 } 1848 1849 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1850 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1851 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1852 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1853 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1854 Depth + 1)) 1855 return true; 1856 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1857 Depth + 1)) 1858 return true; 1859 1860 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1861 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1862 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1863 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1864 Known.One |= Known2.One; 1865 Known.Zero |= Known2.Zero; 1866 } 1867 1868 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1869 if (isPowerOf2_32(BitWidth)) { 1870 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1871 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1872 Known2, TLO, Depth + 1)) 1873 return true; 1874 } 1875 break; 1876 } 1877 case ISD::ROTL: 1878 case ISD::ROTR: { 1879 SDValue Op0 = Op.getOperand(0); 1880 SDValue Op1 = Op.getOperand(1); 1881 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1882 1883 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1884 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1885 return TLO.CombineTo(Op, Op0); 1886 1887 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 1888 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1889 unsigned RevAmt = BitWidth - Amt; 1890 1891 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 1892 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 1893 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 1894 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1895 Depth + 1)) 1896 return true; 1897 1898 // rot*(x, 0) --> x 1899 if (Amt == 0) 1900 return TLO.CombineTo(Op, Op0); 1901 1902 // See if we don't demand either half of the rotated bits. 1903 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 1904 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 1905 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 1906 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 1907 } 1908 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 1909 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 1910 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 1911 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1912 } 1913 } 1914 1915 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1916 if (isPowerOf2_32(BitWidth)) { 1917 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1918 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1919 Depth + 1)) 1920 return true; 1921 } 1922 break; 1923 } 1924 case ISD::UMIN: { 1925 // Check if one arg is always less than (or equal) to the other arg. 1926 SDValue Op0 = Op.getOperand(0); 1927 SDValue Op1 = Op.getOperand(1); 1928 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1929 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1930 Known = KnownBits::umin(Known0, Known1); 1931 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1932 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1933 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1934 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1935 break; 1936 } 1937 case ISD::UMAX: { 1938 // Check if one arg is always greater than (or equal) to the other arg. 1939 SDValue Op0 = Op.getOperand(0); 1940 SDValue Op1 = Op.getOperand(1); 1941 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1942 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1943 Known = KnownBits::umax(Known0, Known1); 1944 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1945 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1946 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1947 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1948 break; 1949 } 1950 case ISD::BITREVERSE: { 1951 SDValue Src = Op.getOperand(0); 1952 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1953 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1954 Depth + 1)) 1955 return true; 1956 Known.One = Known2.One.reverseBits(); 1957 Known.Zero = Known2.Zero.reverseBits(); 1958 break; 1959 } 1960 case ISD::BSWAP: { 1961 SDValue Src = Op.getOperand(0); 1962 1963 // If the only bits demanded come from one byte of the bswap result, 1964 // just shift the input byte into position to eliminate the bswap. 1965 unsigned NLZ = DemandedBits.countLeadingZeros(); 1966 unsigned NTZ = DemandedBits.countTrailingZeros(); 1967 1968 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 1969 // we need all the bits down to bit 8. Likewise, round NLZ. If we 1970 // have 14 leading zeros, round to 8. 1971 NLZ = alignDown(NLZ, 8); 1972 NTZ = alignDown(NTZ, 8); 1973 // If we need exactly one byte, we can do this transformation. 1974 if (BitWidth - NLZ - NTZ == 8) { 1975 // Replace this with either a left or right shift to get the byte into 1976 // the right place. 1977 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 1978 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 1979 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 1980 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 1981 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 1982 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 1983 return TLO.CombineTo(Op, NewOp); 1984 } 1985 } 1986 1987 APInt DemandedSrcBits = DemandedBits.byteSwap(); 1988 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1989 Depth + 1)) 1990 return true; 1991 Known.One = Known2.One.byteSwap(); 1992 Known.Zero = Known2.Zero.byteSwap(); 1993 break; 1994 } 1995 case ISD::CTPOP: { 1996 // If only 1 bit is demanded, replace with PARITY as long as we're before 1997 // op legalization. 1998 // FIXME: Limit to scalars for now. 1999 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2000 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2001 Op.getOperand(0))); 2002 2003 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2004 break; 2005 } 2006 case ISD::SIGN_EXTEND_INREG: { 2007 SDValue Op0 = Op.getOperand(0); 2008 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2009 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2010 2011 // If we only care about the highest bit, don't bother shifting right. 2012 if (DemandedBits.isSignMask()) { 2013 unsigned MinSignedBits = 2014 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2015 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2016 // However if the input is already sign extended we expect the sign 2017 // extension to be dropped altogether later and do not simplify. 2018 if (!AlreadySignExtended) { 2019 // Compute the correct shift amount type, which must be getShiftAmountTy 2020 // for scalar types after legalization. 2021 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2022 getShiftAmountTy(VT, DL)); 2023 return TLO.CombineTo(Op, 2024 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2025 } 2026 } 2027 2028 // If none of the extended bits are demanded, eliminate the sextinreg. 2029 if (DemandedBits.getActiveBits() <= ExVTBits) 2030 return TLO.CombineTo(Op, Op0); 2031 2032 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2033 2034 // Since the sign extended bits are demanded, we know that the sign 2035 // bit is demanded. 2036 InputDemandedBits.setBit(ExVTBits - 1); 2037 2038 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 2039 return true; 2040 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2041 2042 // If the sign bit of the input is known set or clear, then we know the 2043 // top bits of the result. 2044 2045 // If the input sign bit is known zero, convert this into a zero extension. 2046 if (Known.Zero[ExVTBits - 1]) 2047 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2048 2049 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2050 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2051 Known.One.setBitsFrom(ExVTBits); 2052 Known.Zero &= Mask; 2053 } else { // Input sign bit unknown 2054 Known.Zero &= Mask; 2055 Known.One &= Mask; 2056 } 2057 break; 2058 } 2059 case ISD::BUILD_PAIR: { 2060 EVT HalfVT = Op.getOperand(0).getValueType(); 2061 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2062 2063 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2064 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2065 2066 KnownBits KnownLo, KnownHi; 2067 2068 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2069 return true; 2070 2071 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2072 return true; 2073 2074 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2075 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2076 2077 Known.One = KnownLo.One.zext(BitWidth) | 2078 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2079 break; 2080 } 2081 case ISD::ZERO_EXTEND: 2082 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2083 SDValue Src = Op.getOperand(0); 2084 EVT SrcVT = Src.getValueType(); 2085 unsigned InBits = SrcVT.getScalarSizeInBits(); 2086 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2087 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2088 2089 // If none of the top bits are demanded, convert this into an any_extend. 2090 if (DemandedBits.getActiveBits() <= InBits) { 2091 // If we only need the non-extended bits of the bottom element 2092 // then we can just bitcast to the result. 2093 if (IsLE && IsVecInReg && DemandedElts == 1 && 2094 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2095 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2096 2097 unsigned Opc = 2098 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2099 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2100 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2101 } 2102 2103 APInt InDemandedBits = DemandedBits.trunc(InBits); 2104 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 2105 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2106 Depth + 1)) 2107 return true; 2108 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2109 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2110 Known = Known.zext(BitWidth); 2111 2112 // Attempt to avoid multi-use ops if we don't need anything from them. 2113 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2114 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2115 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2116 break; 2117 } 2118 case ISD::SIGN_EXTEND: 2119 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2120 SDValue Src = Op.getOperand(0); 2121 EVT SrcVT = Src.getValueType(); 2122 unsigned InBits = SrcVT.getScalarSizeInBits(); 2123 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2124 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2125 2126 // If none of the top bits are demanded, convert this into an any_extend. 2127 if (DemandedBits.getActiveBits() <= InBits) { 2128 // If we only need the non-extended bits of the bottom element 2129 // then we can just bitcast to the result. 2130 if (IsLE && IsVecInReg && DemandedElts == 1 && 2131 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2132 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2133 2134 unsigned Opc = 2135 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2136 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2137 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2138 } 2139 2140 APInt InDemandedBits = DemandedBits.trunc(InBits); 2141 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 2142 2143 // Since some of the sign extended bits are demanded, we know that the sign 2144 // bit is demanded. 2145 InDemandedBits.setBit(InBits - 1); 2146 2147 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2148 Depth + 1)) 2149 return true; 2150 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2151 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2152 2153 // If the sign bit is known one, the top bits match. 2154 Known = Known.sext(BitWidth); 2155 2156 // If the sign bit is known zero, convert this to a zero extend. 2157 if (Known.isNonNegative()) { 2158 unsigned Opc = 2159 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2160 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2161 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2162 } 2163 2164 // Attempt to avoid multi-use ops if we don't need anything from them. 2165 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2166 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2167 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2168 break; 2169 } 2170 case ISD::ANY_EXTEND: 2171 case ISD::ANY_EXTEND_VECTOR_INREG: { 2172 SDValue Src = Op.getOperand(0); 2173 EVT SrcVT = Src.getValueType(); 2174 unsigned InBits = SrcVT.getScalarSizeInBits(); 2175 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2176 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2177 2178 // If we only need the bottom element then we can just bitcast. 2179 // TODO: Handle ANY_EXTEND? 2180 if (IsLE && IsVecInReg && DemandedElts == 1 && 2181 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2182 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2183 2184 APInt InDemandedBits = DemandedBits.trunc(InBits); 2185 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 2186 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2187 Depth + 1)) 2188 return true; 2189 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2190 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2191 Known = Known.anyext(BitWidth); 2192 2193 // Attempt to avoid multi-use ops if we don't need anything from them. 2194 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2195 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2196 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2197 break; 2198 } 2199 case ISD::TRUNCATE: { 2200 SDValue Src = Op.getOperand(0); 2201 2202 // Simplify the input, using demanded bit information, and compute the known 2203 // zero/one bits live out. 2204 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2205 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2206 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2207 Depth + 1)) 2208 return true; 2209 Known = Known.trunc(BitWidth); 2210 2211 // Attempt to avoid multi-use ops if we don't need anything from them. 2212 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2213 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2214 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2215 2216 // If the input is only used by this truncate, see if we can shrink it based 2217 // on the known demanded bits. 2218 if (Src.getNode()->hasOneUse()) { 2219 switch (Src.getOpcode()) { 2220 default: 2221 break; 2222 case ISD::SRL: 2223 // Shrink SRL by a constant if none of the high bits shifted in are 2224 // demanded. 2225 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2226 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2227 // undesirable. 2228 break; 2229 2230 const APInt *ShAmtC = 2231 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2232 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2233 break; 2234 uint64_t ShVal = ShAmtC->getZExtValue(); 2235 2236 APInt HighBits = 2237 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2238 HighBits.lshrInPlace(ShVal); 2239 HighBits = HighBits.trunc(BitWidth); 2240 2241 if (!(HighBits & DemandedBits)) { 2242 // None of the shifted in bits are needed. Add a truncate of the 2243 // shift input, then shift it. 2244 SDValue NewShAmt = TLO.DAG.getConstant( 2245 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2246 SDValue NewTrunc = 2247 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2248 return TLO.CombineTo( 2249 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2250 } 2251 break; 2252 } 2253 } 2254 2255 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2256 break; 2257 } 2258 case ISD::AssertZext: { 2259 // AssertZext demands all of the high bits, plus any of the low bits 2260 // demanded by its users. 2261 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2262 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2263 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2264 TLO, Depth + 1)) 2265 return true; 2266 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2267 2268 Known.Zero |= ~InMask; 2269 break; 2270 } 2271 case ISD::EXTRACT_VECTOR_ELT: { 2272 SDValue Src = Op.getOperand(0); 2273 SDValue Idx = Op.getOperand(1); 2274 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2275 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2276 2277 if (SrcEltCnt.isScalable()) 2278 return false; 2279 2280 // Demand the bits from every vector element without a constant index. 2281 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2282 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2283 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2284 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2285 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2286 2287 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2288 // anything about the extended bits. 2289 APInt DemandedSrcBits = DemandedBits; 2290 if (BitWidth > EltBitWidth) 2291 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2292 2293 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2294 Depth + 1)) 2295 return true; 2296 2297 // Attempt to avoid multi-use ops if we don't need anything from them. 2298 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2299 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2300 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2301 SDValue NewOp = 2302 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2303 return TLO.CombineTo(Op, NewOp); 2304 } 2305 } 2306 2307 Known = Known2; 2308 if (BitWidth > EltBitWidth) 2309 Known = Known.anyext(BitWidth); 2310 break; 2311 } 2312 case ISD::BITCAST: { 2313 SDValue Src = Op.getOperand(0); 2314 EVT SrcVT = Src.getValueType(); 2315 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2316 2317 // If this is an FP->Int bitcast and if the sign bit is the only 2318 // thing demanded, turn this into a FGETSIGN. 2319 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2320 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2321 SrcVT.isFloatingPoint()) { 2322 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2323 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2324 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2325 SrcVT != MVT::f128) { 2326 // Cannot eliminate/lower SHL for f128 yet. 2327 EVT Ty = OpVTLegal ? VT : MVT::i32; 2328 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2329 // place. We expect the SHL to be eliminated by other optimizations. 2330 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2331 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2332 if (!OpVTLegal && OpVTSizeInBits > 32) 2333 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2334 unsigned ShVal = Op.getValueSizeInBits() - 1; 2335 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2336 return TLO.CombineTo(Op, 2337 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2338 } 2339 } 2340 2341 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2342 // Demand the elt/bit if any of the original elts/bits are demanded. 2343 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2344 unsigned Scale = BitWidth / NumSrcEltBits; 2345 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2346 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2347 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2348 for (unsigned i = 0; i != Scale; ++i) { 2349 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2350 unsigned BitOffset = EltOffset * NumSrcEltBits; 2351 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2352 if (!Sub.isZero()) { 2353 DemandedSrcBits |= Sub; 2354 for (unsigned j = 0; j != NumElts; ++j) 2355 if (DemandedElts[j]) 2356 DemandedSrcElts.setBit((j * Scale) + i); 2357 } 2358 } 2359 2360 APInt KnownSrcUndef, KnownSrcZero; 2361 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2362 KnownSrcZero, TLO, Depth + 1)) 2363 return true; 2364 2365 KnownBits KnownSrcBits; 2366 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2367 KnownSrcBits, TLO, Depth + 1)) 2368 return true; 2369 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2370 // TODO - bigendian once we have test coverage. 2371 unsigned Scale = NumSrcEltBits / BitWidth; 2372 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2373 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2374 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2375 for (unsigned i = 0; i != NumElts; ++i) 2376 if (DemandedElts[i]) { 2377 unsigned Offset = (i % Scale) * BitWidth; 2378 DemandedSrcBits.insertBits(DemandedBits, Offset); 2379 DemandedSrcElts.setBit(i / Scale); 2380 } 2381 2382 if (SrcVT.isVector()) { 2383 APInt KnownSrcUndef, KnownSrcZero; 2384 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2385 KnownSrcZero, TLO, Depth + 1)) 2386 return true; 2387 } 2388 2389 KnownBits KnownSrcBits; 2390 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2391 KnownSrcBits, TLO, Depth + 1)) 2392 return true; 2393 } 2394 2395 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2396 // recursive call where Known may be useful to the caller. 2397 if (Depth > 0) { 2398 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2399 return false; 2400 } 2401 break; 2402 } 2403 case ISD::MUL: 2404 if (DemandedBits.isPowerOf2()) { 2405 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2406 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2407 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2408 unsigned CTZ = DemandedBits.countTrailingZeros(); 2409 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2410 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2411 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2412 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2413 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2414 return TLO.CombineTo(Op, Shl); 2415 } 2416 } 2417 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2418 // X * X is odd iff X is odd. 2419 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2420 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2421 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2422 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2423 return TLO.CombineTo(Op, And1); 2424 } 2425 LLVM_FALLTHROUGH; 2426 case ISD::ADD: 2427 case ISD::SUB: { 2428 // Add, Sub, and Mul don't demand any bits in positions beyond that 2429 // of the highest bit demanded of them. 2430 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2431 SDNodeFlags Flags = Op.getNode()->getFlags(); 2432 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2433 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2434 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2435 Depth + 1) || 2436 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2437 Depth + 1) || 2438 // See if the operation should be performed at a smaller bit width. 2439 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2440 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2441 // Disable the nsw and nuw flags. We can no longer guarantee that we 2442 // won't wrap after simplification. 2443 Flags.setNoSignedWrap(false); 2444 Flags.setNoUnsignedWrap(false); 2445 SDValue NewOp = 2446 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2447 return TLO.CombineTo(Op, NewOp); 2448 } 2449 return true; 2450 } 2451 2452 // Attempt to avoid multi-use ops if we don't need anything from them. 2453 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2454 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2455 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2456 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2457 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2458 if (DemandedOp0 || DemandedOp1) { 2459 Flags.setNoSignedWrap(false); 2460 Flags.setNoUnsignedWrap(false); 2461 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2462 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2463 SDValue NewOp = 2464 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2465 return TLO.CombineTo(Op, NewOp); 2466 } 2467 } 2468 2469 // If we have a constant operand, we may be able to turn it into -1 if we 2470 // do not demand the high bits. This can make the constant smaller to 2471 // encode, allow more general folding, or match specialized instruction 2472 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2473 // is probably not useful (and could be detrimental). 2474 ConstantSDNode *C = isConstOrConstSplat(Op1); 2475 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2476 if (C && !C->isAllOnes() && !C->isOne() && 2477 (C->getAPIntValue() | HighMask).isAllOnes()) { 2478 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2479 // Disable the nsw and nuw flags. We can no longer guarantee that we 2480 // won't wrap after simplification. 2481 Flags.setNoSignedWrap(false); 2482 Flags.setNoUnsignedWrap(false); 2483 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2484 return TLO.CombineTo(Op, NewOp); 2485 } 2486 2487 // Match a multiply with a disguised negated-power-of-2 and convert to a 2488 // an equivalent shift-left amount. 2489 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2490 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2491 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2492 return 0; 2493 2494 // Don't touch opaque constants. Also, ignore zero and power-of-2 2495 // multiplies. Those will get folded later. 2496 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2497 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2498 !MulC->getAPIntValue().isPowerOf2()) { 2499 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2500 if (UnmaskedC.isNegatedPowerOf2()) 2501 return (-UnmaskedC).logBase2(); 2502 } 2503 return 0; 2504 }; 2505 2506 auto foldMul = [&](SDValue X, SDValue Y, unsigned ShlAmt) { 2507 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2508 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2509 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2510 SDValue Sub = TLO.DAG.getNode(ISD::SUB, dl, VT, Y, Shl); 2511 return TLO.CombineTo(Op, Sub); 2512 }; 2513 2514 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2515 if (Op.getOpcode() == ISD::ADD) { 2516 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2517 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2518 return foldMul(Op0.getOperand(0), Op1, ShAmt); 2519 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2520 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2521 return foldMul(Op1.getOperand(0), Op0, ShAmt); 2522 // TODO: 2523 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2524 } 2525 } 2526 2527 LLVM_FALLTHROUGH; 2528 } 2529 default: 2530 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2531 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2532 Known, TLO, Depth)) 2533 return true; 2534 break; 2535 } 2536 2537 // Just use computeKnownBits to compute output bits. 2538 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2539 break; 2540 } 2541 2542 // If we know the value of all of the demanded bits, return this as a 2543 // constant. 2544 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2545 // Avoid folding to a constant if any OpaqueConstant is involved. 2546 const SDNode *N = Op.getNode(); 2547 for (SDNode *Op : 2548 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2550 if (C->isOpaque()) 2551 return false; 2552 } 2553 if (VT.isInteger()) 2554 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2555 if (VT.isFloatingPoint()) 2556 return TLO.CombineTo( 2557 Op, 2558 TLO.DAG.getConstantFP( 2559 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2560 } 2561 2562 return false; 2563 } 2564 2565 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2566 const APInt &DemandedElts, 2567 DAGCombinerInfo &DCI) const { 2568 SelectionDAG &DAG = DCI.DAG; 2569 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2570 !DCI.isBeforeLegalizeOps()); 2571 2572 APInt KnownUndef, KnownZero; 2573 bool Simplified = 2574 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2575 if (Simplified) { 2576 DCI.AddToWorklist(Op.getNode()); 2577 DCI.CommitTargetLoweringOpt(TLO); 2578 } 2579 2580 return Simplified; 2581 } 2582 2583 /// Given a vector binary operation and known undefined elements for each input 2584 /// operand, compute whether each element of the output is undefined. 2585 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2586 const APInt &UndefOp0, 2587 const APInt &UndefOp1) { 2588 EVT VT = BO.getValueType(); 2589 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2590 "Vector binop only"); 2591 2592 EVT EltVT = VT.getVectorElementType(); 2593 unsigned NumElts = VT.getVectorNumElements(); 2594 assert(UndefOp0.getBitWidth() == NumElts && 2595 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2596 2597 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2598 const APInt &UndefVals) { 2599 if (UndefVals[Index]) 2600 return DAG.getUNDEF(EltVT); 2601 2602 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2603 // Try hard to make sure that the getNode() call is not creating temporary 2604 // nodes. Ignore opaque integers because they do not constant fold. 2605 SDValue Elt = BV->getOperand(Index); 2606 auto *C = dyn_cast<ConstantSDNode>(Elt); 2607 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2608 return Elt; 2609 } 2610 2611 return SDValue(); 2612 }; 2613 2614 APInt KnownUndef = APInt::getZero(NumElts); 2615 for (unsigned i = 0; i != NumElts; ++i) { 2616 // If both inputs for this element are either constant or undef and match 2617 // the element type, compute the constant/undef result for this element of 2618 // the vector. 2619 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2620 // not handle FP constants. The code within getNode() should be refactored 2621 // to avoid the danger of creating a bogus temporary node here. 2622 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2623 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2624 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2625 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2626 KnownUndef.setBit(i); 2627 } 2628 return KnownUndef; 2629 } 2630 2631 bool TargetLowering::SimplifyDemandedVectorElts( 2632 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2633 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2634 bool AssumeSingleUse) const { 2635 EVT VT = Op.getValueType(); 2636 unsigned Opcode = Op.getOpcode(); 2637 APInt DemandedElts = OriginalDemandedElts; 2638 unsigned NumElts = DemandedElts.getBitWidth(); 2639 assert(VT.isVector() && "Expected vector op"); 2640 2641 KnownUndef = KnownZero = APInt::getZero(NumElts); 2642 2643 // TODO: For now we assume we know nothing about scalable vectors. 2644 if (VT.isScalableVector()) 2645 return false; 2646 2647 assert(VT.getVectorNumElements() == NumElts && 2648 "Mask size mismatches value type element count!"); 2649 2650 // Undef operand. 2651 if (Op.isUndef()) { 2652 KnownUndef.setAllBits(); 2653 return false; 2654 } 2655 2656 // If Op has other users, assume that all elements are needed. 2657 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2658 DemandedElts.setAllBits(); 2659 2660 // Not demanding any elements from Op. 2661 if (DemandedElts == 0) { 2662 KnownUndef.setAllBits(); 2663 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2664 } 2665 2666 // Limit search depth. 2667 if (Depth >= SelectionDAG::MaxRecursionDepth) 2668 return false; 2669 2670 SDLoc DL(Op); 2671 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2672 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2673 2674 // Helper for demanding the specified elements and all the bits of both binary 2675 // operands. 2676 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2677 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2678 TLO.DAG, Depth + 1); 2679 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2680 TLO.DAG, Depth + 1); 2681 if (NewOp0 || NewOp1) { 2682 SDValue NewOp = TLO.DAG.getNode( 2683 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2684 return TLO.CombineTo(Op, NewOp); 2685 } 2686 return false; 2687 }; 2688 2689 switch (Opcode) { 2690 case ISD::SCALAR_TO_VECTOR: { 2691 if (!DemandedElts[0]) { 2692 KnownUndef.setAllBits(); 2693 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2694 } 2695 SDValue ScalarSrc = Op.getOperand(0); 2696 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2697 SDValue Src = ScalarSrc.getOperand(0); 2698 SDValue Idx = ScalarSrc.getOperand(1); 2699 EVT SrcVT = Src.getValueType(); 2700 2701 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2702 2703 if (SrcEltCnt.isScalable()) 2704 return false; 2705 2706 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2707 if (isNullConstant(Idx)) { 2708 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2709 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2710 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2711 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2712 TLO, Depth + 1)) 2713 return true; 2714 } 2715 } 2716 KnownUndef.setHighBits(NumElts - 1); 2717 break; 2718 } 2719 case ISD::BITCAST: { 2720 SDValue Src = Op.getOperand(0); 2721 EVT SrcVT = Src.getValueType(); 2722 2723 // We only handle vectors here. 2724 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2725 if (!SrcVT.isVector()) 2726 break; 2727 2728 // Fast handling of 'identity' bitcasts. 2729 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2730 if (NumSrcElts == NumElts) 2731 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2732 KnownZero, TLO, Depth + 1); 2733 2734 APInt SrcDemandedElts, SrcZero, SrcUndef; 2735 2736 // Bitcast from 'large element' src vector to 'small element' vector, we 2737 // must demand a source element if any DemandedElt maps to it. 2738 if ((NumElts % NumSrcElts) == 0) { 2739 unsigned Scale = NumElts / NumSrcElts; 2740 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2741 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2742 TLO, Depth + 1)) 2743 return true; 2744 2745 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2746 // of the large element. 2747 // TODO - bigendian once we have test coverage. 2748 if (IsLE) { 2749 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2750 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2751 for (unsigned i = 0; i != NumElts; ++i) 2752 if (DemandedElts[i]) { 2753 unsigned Ofs = (i % Scale) * EltSizeInBits; 2754 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2755 } 2756 2757 KnownBits Known; 2758 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2759 TLO, Depth + 1)) 2760 return true; 2761 } 2762 2763 // If the src element is zero/undef then all the output elements will be - 2764 // only demanded elements are guaranteed to be correct. 2765 for (unsigned i = 0; i != NumSrcElts; ++i) { 2766 if (SrcDemandedElts[i]) { 2767 if (SrcZero[i]) 2768 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2769 if (SrcUndef[i]) 2770 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2771 } 2772 } 2773 } 2774 2775 // Bitcast from 'small element' src vector to 'large element' vector, we 2776 // demand all smaller source elements covered by the larger demanded element 2777 // of this vector. 2778 if ((NumSrcElts % NumElts) == 0) { 2779 unsigned Scale = NumSrcElts / NumElts; 2780 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2781 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2782 TLO, Depth + 1)) 2783 return true; 2784 2785 // If all the src elements covering an output element are zero/undef, then 2786 // the output element will be as well, assuming it was demanded. 2787 for (unsigned i = 0; i != NumElts; ++i) { 2788 if (DemandedElts[i]) { 2789 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2790 KnownZero.setBit(i); 2791 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2792 KnownUndef.setBit(i); 2793 } 2794 } 2795 } 2796 break; 2797 } 2798 case ISD::BUILD_VECTOR: { 2799 // Check all elements and simplify any unused elements with UNDEF. 2800 if (!DemandedElts.isAllOnes()) { 2801 // Don't simplify BROADCASTS. 2802 if (llvm::any_of(Op->op_values(), 2803 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2804 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2805 bool Updated = false; 2806 for (unsigned i = 0; i != NumElts; ++i) { 2807 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2808 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2809 KnownUndef.setBit(i); 2810 Updated = true; 2811 } 2812 } 2813 if (Updated) 2814 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2815 } 2816 } 2817 for (unsigned i = 0; i != NumElts; ++i) { 2818 SDValue SrcOp = Op.getOperand(i); 2819 if (SrcOp.isUndef()) { 2820 KnownUndef.setBit(i); 2821 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2822 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2823 KnownZero.setBit(i); 2824 } 2825 } 2826 break; 2827 } 2828 case ISD::CONCAT_VECTORS: { 2829 EVT SubVT = Op.getOperand(0).getValueType(); 2830 unsigned NumSubVecs = Op.getNumOperands(); 2831 unsigned NumSubElts = SubVT.getVectorNumElements(); 2832 for (unsigned i = 0; i != NumSubVecs; ++i) { 2833 SDValue SubOp = Op.getOperand(i); 2834 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2835 APInt SubUndef, SubZero; 2836 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2837 Depth + 1)) 2838 return true; 2839 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2840 KnownZero.insertBits(SubZero, i * NumSubElts); 2841 } 2842 break; 2843 } 2844 case ISD::INSERT_SUBVECTOR: { 2845 // Demand any elements from the subvector and the remainder from the src its 2846 // inserted into. 2847 SDValue Src = Op.getOperand(0); 2848 SDValue Sub = Op.getOperand(1); 2849 uint64_t Idx = Op.getConstantOperandVal(2); 2850 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2851 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2852 APInt DemandedSrcElts = DemandedElts; 2853 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2854 2855 APInt SubUndef, SubZero; 2856 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2857 Depth + 1)) 2858 return true; 2859 2860 // If none of the src operand elements are demanded, replace it with undef. 2861 if (!DemandedSrcElts && !Src.isUndef()) 2862 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2863 TLO.DAG.getUNDEF(VT), Sub, 2864 Op.getOperand(2))); 2865 2866 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2867 TLO, Depth + 1)) 2868 return true; 2869 KnownUndef.insertBits(SubUndef, Idx); 2870 KnownZero.insertBits(SubZero, Idx); 2871 2872 // Attempt to avoid multi-use ops if we don't need anything from them. 2873 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 2874 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2875 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2876 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2877 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2878 if (NewSrc || NewSub) { 2879 NewSrc = NewSrc ? NewSrc : Src; 2880 NewSub = NewSub ? NewSub : Sub; 2881 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2882 NewSub, Op.getOperand(2)); 2883 return TLO.CombineTo(Op, NewOp); 2884 } 2885 } 2886 break; 2887 } 2888 case ISD::EXTRACT_SUBVECTOR: { 2889 // Offset the demanded elts by the subvector index. 2890 SDValue Src = Op.getOperand(0); 2891 if (Src.getValueType().isScalableVector()) 2892 break; 2893 uint64_t Idx = Op.getConstantOperandVal(1); 2894 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2895 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2896 2897 APInt SrcUndef, SrcZero; 2898 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2899 Depth + 1)) 2900 return true; 2901 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2902 KnownZero = SrcZero.extractBits(NumElts, Idx); 2903 2904 // Attempt to avoid multi-use ops if we don't need anything from them. 2905 if (!DemandedElts.isAllOnes()) { 2906 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2907 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2908 if (NewSrc) { 2909 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2910 Op.getOperand(1)); 2911 return TLO.CombineTo(Op, NewOp); 2912 } 2913 } 2914 break; 2915 } 2916 case ISD::INSERT_VECTOR_ELT: { 2917 SDValue Vec = Op.getOperand(0); 2918 SDValue Scl = Op.getOperand(1); 2919 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2920 2921 // For a legal, constant insertion index, if we don't need this insertion 2922 // then strip it, else remove it from the demanded elts. 2923 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2924 unsigned Idx = CIdx->getZExtValue(); 2925 if (!DemandedElts[Idx]) 2926 return TLO.CombineTo(Op, Vec); 2927 2928 APInt DemandedVecElts(DemandedElts); 2929 DemandedVecElts.clearBit(Idx); 2930 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2931 KnownZero, TLO, Depth + 1)) 2932 return true; 2933 2934 KnownUndef.setBitVal(Idx, Scl.isUndef()); 2935 2936 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 2937 break; 2938 } 2939 2940 APInt VecUndef, VecZero; 2941 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2942 Depth + 1)) 2943 return true; 2944 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2945 break; 2946 } 2947 case ISD::VSELECT: { 2948 // Try to transform the select condition based on the current demanded 2949 // elements. 2950 // TODO: If a condition element is undef, we can choose from one arm of the 2951 // select (and if one arm is undef, then we can propagate that to the 2952 // result). 2953 // TODO - add support for constant vselect masks (see IR version of this). 2954 APInt UnusedUndef, UnusedZero; 2955 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 2956 UnusedZero, TLO, Depth + 1)) 2957 return true; 2958 2959 // See if we can simplify either vselect operand. 2960 APInt DemandedLHS(DemandedElts); 2961 APInt DemandedRHS(DemandedElts); 2962 APInt UndefLHS, ZeroLHS; 2963 APInt UndefRHS, ZeroRHS; 2964 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 2965 ZeroLHS, TLO, Depth + 1)) 2966 return true; 2967 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 2968 ZeroRHS, TLO, Depth + 1)) 2969 return true; 2970 2971 KnownUndef = UndefLHS & UndefRHS; 2972 KnownZero = ZeroLHS & ZeroRHS; 2973 break; 2974 } 2975 case ISD::VECTOR_SHUFFLE: { 2976 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 2977 2978 // Collect demanded elements from shuffle operands.. 2979 APInt DemandedLHS(NumElts, 0); 2980 APInt DemandedRHS(NumElts, 0); 2981 for (unsigned i = 0; i != NumElts; ++i) { 2982 int M = ShuffleMask[i]; 2983 if (M < 0 || !DemandedElts[i]) 2984 continue; 2985 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 2986 if (M < (int)NumElts) 2987 DemandedLHS.setBit(M); 2988 else 2989 DemandedRHS.setBit(M - NumElts); 2990 } 2991 2992 // See if we can simplify either shuffle operand. 2993 APInt UndefLHS, ZeroLHS; 2994 APInt UndefRHS, ZeroRHS; 2995 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 2996 ZeroLHS, TLO, Depth + 1)) 2997 return true; 2998 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 2999 ZeroRHS, TLO, Depth + 1)) 3000 return true; 3001 3002 // Simplify mask using undef elements from LHS/RHS. 3003 bool Updated = false; 3004 bool IdentityLHS = true, IdentityRHS = true; 3005 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3006 for (unsigned i = 0; i != NumElts; ++i) { 3007 int &M = NewMask[i]; 3008 if (M < 0) 3009 continue; 3010 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3011 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3012 Updated = true; 3013 M = -1; 3014 } 3015 IdentityLHS &= (M < 0) || (M == (int)i); 3016 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3017 } 3018 3019 // Update legal shuffle masks based on demanded elements if it won't reduce 3020 // to Identity which can cause premature removal of the shuffle mask. 3021 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3022 SDValue LegalShuffle = 3023 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3024 NewMask, TLO.DAG); 3025 if (LegalShuffle) 3026 return TLO.CombineTo(Op, LegalShuffle); 3027 } 3028 3029 // Propagate undef/zero elements from LHS/RHS. 3030 for (unsigned i = 0; i != NumElts; ++i) { 3031 int M = ShuffleMask[i]; 3032 if (M < 0) { 3033 KnownUndef.setBit(i); 3034 } else if (M < (int)NumElts) { 3035 if (UndefLHS[M]) 3036 KnownUndef.setBit(i); 3037 if (ZeroLHS[M]) 3038 KnownZero.setBit(i); 3039 } else { 3040 if (UndefRHS[M - NumElts]) 3041 KnownUndef.setBit(i); 3042 if (ZeroRHS[M - NumElts]) 3043 KnownZero.setBit(i); 3044 } 3045 } 3046 break; 3047 } 3048 case ISD::ANY_EXTEND_VECTOR_INREG: 3049 case ISD::SIGN_EXTEND_VECTOR_INREG: 3050 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3051 APInt SrcUndef, SrcZero; 3052 SDValue Src = Op.getOperand(0); 3053 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3054 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 3055 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3056 Depth + 1)) 3057 return true; 3058 KnownZero = SrcZero.zextOrTrunc(NumElts); 3059 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3060 3061 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3062 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3063 DemandedSrcElts == 1) { 3064 // aext - if we just need the bottom element then we can bitcast. 3065 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3066 } 3067 3068 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3069 // zext(undef) upper bits are guaranteed to be zero. 3070 if (DemandedElts.isSubsetOf(KnownUndef)) 3071 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3072 KnownUndef.clearAllBits(); 3073 3074 // zext - if we just need the bottom element then we can mask: 3075 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3076 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3077 Op->isOnlyUserOf(Src.getNode()) && 3078 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3079 SDLoc DL(Op); 3080 EVT SrcVT = Src.getValueType(); 3081 EVT SrcSVT = SrcVT.getScalarType(); 3082 SmallVector<SDValue> MaskElts; 3083 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3084 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3085 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3086 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3087 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3088 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3089 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3090 } 3091 } 3092 } 3093 break; 3094 } 3095 3096 // TODO: There are more binop opcodes that could be handled here - MIN, 3097 // MAX, saturated math, etc. 3098 case ISD::ADD: { 3099 SDValue Op0 = Op.getOperand(0); 3100 SDValue Op1 = Op.getOperand(1); 3101 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3102 APInt UndefLHS, ZeroLHS; 3103 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3104 Depth + 1, /*AssumeSingleUse*/ true)) 3105 return true; 3106 } 3107 LLVM_FALLTHROUGH; 3108 } 3109 case ISD::OR: 3110 case ISD::XOR: 3111 case ISD::SUB: 3112 case ISD::FADD: 3113 case ISD::FSUB: 3114 case ISD::FMUL: 3115 case ISD::FDIV: 3116 case ISD::FREM: { 3117 SDValue Op0 = Op.getOperand(0); 3118 SDValue Op1 = Op.getOperand(1); 3119 3120 APInt UndefRHS, ZeroRHS; 3121 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3122 Depth + 1)) 3123 return true; 3124 APInt UndefLHS, ZeroLHS; 3125 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3126 Depth + 1)) 3127 return true; 3128 3129 KnownZero = ZeroLHS & ZeroRHS; 3130 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3131 3132 // Attempt to avoid multi-use ops if we don't need anything from them. 3133 // TODO - use KnownUndef to relax the demandedelts? 3134 if (!DemandedElts.isAllOnes()) 3135 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3136 return true; 3137 break; 3138 } 3139 case ISD::SHL: 3140 case ISD::SRL: 3141 case ISD::SRA: 3142 case ISD::ROTL: 3143 case ISD::ROTR: { 3144 SDValue Op0 = Op.getOperand(0); 3145 SDValue Op1 = Op.getOperand(1); 3146 3147 APInt UndefRHS, ZeroRHS; 3148 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3149 Depth + 1)) 3150 return true; 3151 APInt UndefLHS, ZeroLHS; 3152 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3153 Depth + 1)) 3154 return true; 3155 3156 KnownZero = ZeroLHS; 3157 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3158 3159 // Attempt to avoid multi-use ops if we don't need anything from them. 3160 // TODO - use KnownUndef to relax the demandedelts? 3161 if (!DemandedElts.isAllOnes()) 3162 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3163 return true; 3164 break; 3165 } 3166 case ISD::MUL: 3167 case ISD::AND: { 3168 SDValue Op0 = Op.getOperand(0); 3169 SDValue Op1 = Op.getOperand(1); 3170 3171 APInt SrcUndef, SrcZero; 3172 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3173 Depth + 1)) 3174 return true; 3175 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3176 TLO, Depth + 1)) 3177 return true; 3178 3179 // If either side has a zero element, then the result element is zero, even 3180 // if the other is an UNDEF. 3181 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3182 // and then handle 'and' nodes with the rest of the binop opcodes. 3183 KnownZero |= SrcZero; 3184 KnownUndef &= SrcUndef; 3185 KnownUndef &= ~KnownZero; 3186 3187 // Attempt to avoid multi-use ops if we don't need anything from them. 3188 // TODO - use KnownUndef to relax the demandedelts? 3189 if (!DemandedElts.isAllOnes()) 3190 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3191 return true; 3192 break; 3193 } 3194 case ISD::TRUNCATE: 3195 case ISD::SIGN_EXTEND: 3196 case ISD::ZERO_EXTEND: 3197 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3198 KnownZero, TLO, Depth + 1)) 3199 return true; 3200 3201 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3202 // zext(undef) upper bits are guaranteed to be zero. 3203 if (DemandedElts.isSubsetOf(KnownUndef)) 3204 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3205 KnownUndef.clearAllBits(); 3206 } 3207 break; 3208 default: { 3209 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3210 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3211 KnownZero, TLO, Depth)) 3212 return true; 3213 } else { 3214 KnownBits Known; 3215 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3216 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3217 TLO, Depth, AssumeSingleUse)) 3218 return true; 3219 } 3220 break; 3221 } 3222 } 3223 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3224 3225 // Constant fold all undef cases. 3226 // TODO: Handle zero cases as well. 3227 if (DemandedElts.isSubsetOf(KnownUndef)) 3228 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3229 3230 return false; 3231 } 3232 3233 /// Determine which of the bits specified in Mask are known to be either zero or 3234 /// one and return them in the Known. 3235 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3236 KnownBits &Known, 3237 const APInt &DemandedElts, 3238 const SelectionDAG &DAG, 3239 unsigned Depth) const { 3240 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3241 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3242 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3243 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3244 "Should use MaskedValueIsZero if you don't know whether Op" 3245 " is a target node!"); 3246 Known.resetAll(); 3247 } 3248 3249 void TargetLowering::computeKnownBitsForTargetInstr( 3250 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3251 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3252 unsigned Depth) const { 3253 Known.resetAll(); 3254 } 3255 3256 void TargetLowering::computeKnownBitsForFrameIndex( 3257 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3258 // The low bits are known zero if the pointer is aligned. 3259 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3260 } 3261 3262 Align TargetLowering::computeKnownAlignForTargetInstr( 3263 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3264 unsigned Depth) const { 3265 return Align(1); 3266 } 3267 3268 /// This method can be implemented by targets that want to expose additional 3269 /// information about sign bits to the DAG Combiner. 3270 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3271 const APInt &, 3272 const SelectionDAG &, 3273 unsigned Depth) const { 3274 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3275 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3276 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3277 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3278 "Should use ComputeNumSignBits if you don't know whether Op" 3279 " is a target node!"); 3280 return 1; 3281 } 3282 3283 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3284 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3285 const MachineRegisterInfo &MRI, unsigned Depth) const { 3286 return 1; 3287 } 3288 3289 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3290 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3291 TargetLoweringOpt &TLO, unsigned Depth) const { 3292 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3293 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3294 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3295 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3296 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3297 " is a target node!"); 3298 return false; 3299 } 3300 3301 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3302 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3303 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3304 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3305 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3306 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3307 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3308 "Should use SimplifyDemandedBits if you don't know whether Op" 3309 " is a target node!"); 3310 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3311 return false; 3312 } 3313 3314 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3315 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3316 SelectionDAG &DAG, unsigned Depth) const { 3317 assert( 3318 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3319 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3320 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3321 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3322 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3323 " is a target node!"); 3324 return SDValue(); 3325 } 3326 3327 SDValue 3328 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3329 SDValue N1, MutableArrayRef<int> Mask, 3330 SelectionDAG &DAG) const { 3331 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3332 if (!LegalMask) { 3333 std::swap(N0, N1); 3334 ShuffleVectorSDNode::commuteMask(Mask); 3335 LegalMask = isShuffleMaskLegal(Mask, VT); 3336 } 3337 3338 if (!LegalMask) 3339 return SDValue(); 3340 3341 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3342 } 3343 3344 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3345 return nullptr; 3346 } 3347 3348 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3349 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3350 bool PoisonOnly, unsigned Depth) const { 3351 assert( 3352 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3353 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3354 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3355 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3356 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3357 " is a target node!"); 3358 return false; 3359 } 3360 3361 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3362 const SelectionDAG &DAG, 3363 bool SNaN, 3364 unsigned Depth) const { 3365 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3366 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3367 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3368 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3369 "Should use isKnownNeverNaN if you don't know whether Op" 3370 " is a target node!"); 3371 return false; 3372 } 3373 3374 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3375 const APInt &DemandedElts, 3376 APInt &UndefElts, 3377 unsigned Depth) const { 3378 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3379 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3380 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3381 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3382 "Should use isSplatValue if you don't know whether Op" 3383 " is a target node!"); 3384 return false; 3385 } 3386 3387 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3388 // work with truncating build vectors and vectors with elements of less than 3389 // 8 bits. 3390 bool TargetLowering::isConstTrueVal(SDValue N) const { 3391 if (!N) 3392 return false; 3393 3394 unsigned EltWidth; 3395 APInt CVal; 3396 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3397 /*AllowTruncation=*/true)) { 3398 CVal = CN->getAPIntValue(); 3399 EltWidth = N.getValueType().getScalarSizeInBits(); 3400 } else 3401 return false; 3402 3403 // If this is a truncating splat, truncate the splat value. 3404 // Otherwise, we may fail to match the expected values below. 3405 if (EltWidth < CVal.getBitWidth()) 3406 CVal = CVal.trunc(EltWidth); 3407 3408 switch (getBooleanContents(N.getValueType())) { 3409 case UndefinedBooleanContent: 3410 return CVal[0]; 3411 case ZeroOrOneBooleanContent: 3412 return CVal.isOne(); 3413 case ZeroOrNegativeOneBooleanContent: 3414 return CVal.isAllOnes(); 3415 } 3416 3417 llvm_unreachable("Invalid boolean contents"); 3418 } 3419 3420 bool TargetLowering::isConstFalseVal(SDValue N) const { 3421 if (!N) 3422 return false; 3423 3424 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3425 if (!CN) { 3426 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3427 if (!BV) 3428 return false; 3429 3430 // Only interested in constant splats, we don't care about undef 3431 // elements in identifying boolean constants and getConstantSplatNode 3432 // returns NULL if all ops are undef; 3433 CN = BV->getConstantSplatNode(); 3434 if (!CN) 3435 return false; 3436 } 3437 3438 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3439 return !CN->getAPIntValue()[0]; 3440 3441 return CN->isZero(); 3442 } 3443 3444 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3445 bool SExt) const { 3446 if (VT == MVT::i1) 3447 return N->isOne(); 3448 3449 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3450 switch (Cnt) { 3451 case TargetLowering::ZeroOrOneBooleanContent: 3452 // An extended value of 1 is always true, unless its original type is i1, 3453 // in which case it will be sign extended to -1. 3454 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3455 case TargetLowering::UndefinedBooleanContent: 3456 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3457 return N->isAllOnes() && SExt; 3458 } 3459 llvm_unreachable("Unexpected enumeration."); 3460 } 3461 3462 /// This helper function of SimplifySetCC tries to optimize the comparison when 3463 /// either operand of the SetCC node is a bitwise-and instruction. 3464 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3465 ISD::CondCode Cond, const SDLoc &DL, 3466 DAGCombinerInfo &DCI) const { 3467 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3468 std::swap(N0, N1); 3469 3470 SelectionDAG &DAG = DCI.DAG; 3471 EVT OpVT = N0.getValueType(); 3472 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3473 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3474 return SDValue(); 3475 3476 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3477 // iff everything but LSB is known zero: 3478 if (Cond == ISD::SETNE && isNullConstant(N1) && 3479 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3480 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3481 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3482 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3483 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3484 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3485 } 3486 3487 // Match these patterns in any of their permutations: 3488 // (X & Y) == Y 3489 // (X & Y) != Y 3490 SDValue X, Y; 3491 if (N0.getOperand(0) == N1) { 3492 X = N0.getOperand(1); 3493 Y = N0.getOperand(0); 3494 } else if (N0.getOperand(1) == N1) { 3495 X = N0.getOperand(0); 3496 Y = N0.getOperand(1); 3497 } else { 3498 return SDValue(); 3499 } 3500 3501 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3502 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3503 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3504 // Note that where Y is variable and is known to have at most one bit set 3505 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3506 // equivalent when Y == 0. 3507 assert(OpVT.isInteger()); 3508 Cond = ISD::getSetCCInverse(Cond, OpVT); 3509 if (DCI.isBeforeLegalizeOps() || 3510 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3511 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3512 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3513 // If the target supports an 'and-not' or 'and-complement' logic operation, 3514 // try to use that to make a comparison operation more efficient. 3515 // But don't do this transform if the mask is a single bit because there are 3516 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3517 // 'rlwinm' on PPC). 3518 3519 // Bail out if the compare operand that we want to turn into a zero is 3520 // already a zero (otherwise, infinite loop). 3521 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3522 if (YConst && YConst->isZero()) 3523 return SDValue(); 3524 3525 // Transform this into: ~X & Y == 0. 3526 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3527 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3528 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3529 } 3530 3531 return SDValue(); 3532 } 3533 3534 /// There are multiple IR patterns that could be checking whether certain 3535 /// truncation of a signed number would be lossy or not. The pattern which is 3536 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3537 /// We are looking for the following pattern: (KeptBits is a constant) 3538 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3539 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3540 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3541 /// We will unfold it into the natural trunc+sext pattern: 3542 /// ((%x << C) a>> C) dstcond %x 3543 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3544 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3545 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3546 const SDLoc &DL) const { 3547 // We must be comparing with a constant. 3548 ConstantSDNode *C1; 3549 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3550 return SDValue(); 3551 3552 // N0 should be: add %x, (1 << (KeptBits-1)) 3553 if (N0->getOpcode() != ISD::ADD) 3554 return SDValue(); 3555 3556 // And we must be 'add'ing a constant. 3557 ConstantSDNode *C01; 3558 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3559 return SDValue(); 3560 3561 SDValue X = N0->getOperand(0); 3562 EVT XVT = X.getValueType(); 3563 3564 // Validate constants ... 3565 3566 APInt I1 = C1->getAPIntValue(); 3567 3568 ISD::CondCode NewCond; 3569 if (Cond == ISD::CondCode::SETULT) { 3570 NewCond = ISD::CondCode::SETEQ; 3571 } else if (Cond == ISD::CondCode::SETULE) { 3572 NewCond = ISD::CondCode::SETEQ; 3573 // But need to 'canonicalize' the constant. 3574 I1 += 1; 3575 } else if (Cond == ISD::CondCode::SETUGT) { 3576 NewCond = ISD::CondCode::SETNE; 3577 // But need to 'canonicalize' the constant. 3578 I1 += 1; 3579 } else if (Cond == ISD::CondCode::SETUGE) { 3580 NewCond = ISD::CondCode::SETNE; 3581 } else 3582 return SDValue(); 3583 3584 APInt I01 = C01->getAPIntValue(); 3585 3586 auto checkConstants = [&I1, &I01]() -> bool { 3587 // Both of them must be power-of-two, and the constant from setcc is bigger. 3588 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3589 }; 3590 3591 if (checkConstants()) { 3592 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3593 } else { 3594 // What if we invert constants? (and the target predicate) 3595 I1.negate(); 3596 I01.negate(); 3597 assert(XVT.isInteger()); 3598 NewCond = getSetCCInverse(NewCond, XVT); 3599 if (!checkConstants()) 3600 return SDValue(); 3601 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3602 } 3603 3604 // They are power-of-two, so which bit is set? 3605 const unsigned KeptBits = I1.logBase2(); 3606 const unsigned KeptBitsMinusOne = I01.logBase2(); 3607 3608 // Magic! 3609 if (KeptBits != (KeptBitsMinusOne + 1)) 3610 return SDValue(); 3611 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3612 3613 // We don't want to do this in every single case. 3614 SelectionDAG &DAG = DCI.DAG; 3615 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3616 XVT, KeptBits)) 3617 return SDValue(); 3618 3619 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3620 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3621 3622 // Unfold into: ((%x << C) a>> C) cond %x 3623 // Where 'cond' will be either 'eq' or 'ne'. 3624 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3625 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3626 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3627 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3628 3629 return T2; 3630 } 3631 3632 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3633 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3634 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3635 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3636 assert(isConstOrConstSplat(N1C) && 3637 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3638 "Should be a comparison with 0."); 3639 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3640 "Valid only for [in]equality comparisons."); 3641 3642 unsigned NewShiftOpcode; 3643 SDValue X, C, Y; 3644 3645 SelectionDAG &DAG = DCI.DAG; 3646 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3647 3648 // Look for '(C l>>/<< Y)'. 3649 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3650 // The shift should be one-use. 3651 if (!V.hasOneUse()) 3652 return false; 3653 unsigned OldShiftOpcode = V.getOpcode(); 3654 switch (OldShiftOpcode) { 3655 case ISD::SHL: 3656 NewShiftOpcode = ISD::SRL; 3657 break; 3658 case ISD::SRL: 3659 NewShiftOpcode = ISD::SHL; 3660 break; 3661 default: 3662 return false; // must be a logical shift. 3663 } 3664 // We should be shifting a constant. 3665 // FIXME: best to use isConstantOrConstantVector(). 3666 C = V.getOperand(0); 3667 ConstantSDNode *CC = 3668 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3669 if (!CC) 3670 return false; 3671 Y = V.getOperand(1); 3672 3673 ConstantSDNode *XC = 3674 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3675 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3676 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3677 }; 3678 3679 // LHS of comparison should be an one-use 'and'. 3680 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3681 return SDValue(); 3682 3683 X = N0.getOperand(0); 3684 SDValue Mask = N0.getOperand(1); 3685 3686 // 'and' is commutative! 3687 if (!Match(Mask)) { 3688 std::swap(X, Mask); 3689 if (!Match(Mask)) 3690 return SDValue(); 3691 } 3692 3693 EVT VT = X.getValueType(); 3694 3695 // Produce: 3696 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3697 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3698 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3699 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3700 return T2; 3701 } 3702 3703 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3704 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3705 /// handle the commuted versions of these patterns. 3706 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3707 ISD::CondCode Cond, const SDLoc &DL, 3708 DAGCombinerInfo &DCI) const { 3709 unsigned BOpcode = N0.getOpcode(); 3710 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3711 "Unexpected binop"); 3712 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3713 3714 // (X + Y) == X --> Y == 0 3715 // (X - Y) == X --> Y == 0 3716 // (X ^ Y) == X --> Y == 0 3717 SelectionDAG &DAG = DCI.DAG; 3718 EVT OpVT = N0.getValueType(); 3719 SDValue X = N0.getOperand(0); 3720 SDValue Y = N0.getOperand(1); 3721 if (X == N1) 3722 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3723 3724 if (Y != N1) 3725 return SDValue(); 3726 3727 // (X + Y) == Y --> X == 0 3728 // (X ^ Y) == Y --> X == 0 3729 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3730 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3731 3732 // The shift would not be valid if the operands are boolean (i1). 3733 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3734 return SDValue(); 3735 3736 // (X - Y) == Y --> X == Y << 1 3737 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3738 !DCI.isBeforeLegalize()); 3739 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3740 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3741 if (!DCI.isCalledByLegalizer()) 3742 DCI.AddToWorklist(YShl1.getNode()); 3743 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3744 } 3745 3746 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3747 SDValue N0, const APInt &C1, 3748 ISD::CondCode Cond, const SDLoc &dl, 3749 SelectionDAG &DAG) { 3750 // Look through truncs that don't change the value of a ctpop. 3751 // FIXME: Add vector support? Need to be careful with setcc result type below. 3752 SDValue CTPOP = N0; 3753 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3754 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3755 CTPOP = N0.getOperand(0); 3756 3757 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3758 return SDValue(); 3759 3760 EVT CTVT = CTPOP.getValueType(); 3761 SDValue CTOp = CTPOP.getOperand(0); 3762 3763 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3764 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3765 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3766 return SDValue(); 3767 3768 // (ctpop x) u< 2 -> (x & x-1) == 0 3769 // (ctpop x) u> 1 -> (x & x-1) != 0 3770 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3771 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3772 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3773 return SDValue(); 3774 if (C1 == 0 && (Cond == ISD::SETULT)) 3775 return SDValue(); // This is handled elsewhere. 3776 3777 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3778 3779 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3780 SDValue Result = CTOp; 3781 for (unsigned i = 0; i < Passes; i++) { 3782 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3783 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3784 } 3785 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3786 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3787 } 3788 3789 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3790 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3791 // For scalars, keep CTPOP if it is legal or custom. 3792 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3793 return SDValue(); 3794 // This is based on X86's custom lowering for CTPOP which produces more 3795 // instructions than the expansion here. 3796 3797 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3798 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3799 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3800 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3801 assert(CTVT.isInteger()); 3802 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3803 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3804 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3805 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3806 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3807 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3808 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3809 } 3810 3811 return SDValue(); 3812 } 3813 3814 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3815 ISD::CondCode Cond, const SDLoc &dl, 3816 SelectionDAG &DAG) { 3817 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3818 return SDValue(); 3819 3820 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3821 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3822 return SDValue(); 3823 3824 auto getRotateSource = [](SDValue X) { 3825 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3826 return X.getOperand(0); 3827 return SDValue(); 3828 }; 3829 3830 // Peek through a rotated value compared against 0 or -1: 3831 // (rot X, Y) == 0/-1 --> X == 0/-1 3832 // (rot X, Y) != 0/-1 --> X != 0/-1 3833 if (SDValue R = getRotateSource(N0)) 3834 return DAG.getSetCC(dl, VT, R, N1, Cond); 3835 3836 // Peek through an 'or' of a rotated value compared against 0: 3837 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 3838 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 3839 // 3840 // TODO: Add the 'and' with -1 sibling. 3841 // TODO: Recurse through a series of 'or' ops to find the rotate. 3842 EVT OpVT = N0.getValueType(); 3843 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 3844 if (SDValue R = getRotateSource(N0.getOperand(0))) { 3845 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 3846 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3847 } 3848 if (SDValue R = getRotateSource(N0.getOperand(1))) { 3849 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 3850 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3851 } 3852 } 3853 3854 return SDValue(); 3855 } 3856 3857 /// Try to simplify a setcc built with the specified operands and cc. If it is 3858 /// unable to simplify it, return a null SDValue. 3859 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3860 ISD::CondCode Cond, bool foldBooleans, 3861 DAGCombinerInfo &DCI, 3862 const SDLoc &dl) const { 3863 SelectionDAG &DAG = DCI.DAG; 3864 const DataLayout &Layout = DAG.getDataLayout(); 3865 EVT OpVT = N0.getValueType(); 3866 3867 // Constant fold or commute setcc. 3868 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 3869 return Fold; 3870 3871 // Ensure that the constant occurs on the RHS and fold constant comparisons. 3872 // TODO: Handle non-splat vector constants. All undef causes trouble. 3873 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 3874 // infinite loop here when we encounter one. 3875 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 3876 if (isConstOrConstSplat(N0) && 3877 (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) && 3878 (DCI.isBeforeLegalizeOps() || 3879 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 3880 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3881 3882 // If we have a subtract with the same 2 non-constant operands as this setcc 3883 // -- but in reverse order -- then try to commute the operands of this setcc 3884 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 3885 // instruction on some targets. 3886 if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) && 3887 (DCI.isBeforeLegalizeOps() || 3888 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 3889 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 3890 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 3891 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3892 3893 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 3894 return V; 3895 3896 if (auto *N1C = isConstOrConstSplat(N1)) { 3897 const APInt &C1 = N1C->getAPIntValue(); 3898 3899 // Optimize some CTPOP cases. 3900 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 3901 return V; 3902 3903 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 3904 // equality comparison, then we're just comparing whether X itself is 3905 // zero. 3906 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 3907 N0.getOperand(0).getOpcode() == ISD::CTLZ && 3908 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 3909 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 3910 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3911 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 3912 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 3913 // (srl (ctlz x), 5) == 0 -> X != 0 3914 // (srl (ctlz x), 5) != 1 -> X != 0 3915 Cond = ISD::SETNE; 3916 } else { 3917 // (srl (ctlz x), 5) != 0 -> X == 0 3918 // (srl (ctlz x), 5) == 1 -> X == 0 3919 Cond = ISD::SETEQ; 3920 } 3921 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 3922 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 3923 Cond); 3924 } 3925 } 3926 } 3927 } 3928 3929 // FIXME: Support vectors. 3930 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 3931 const APInt &C1 = N1C->getAPIntValue(); 3932 3933 // (zext x) == C --> x == (trunc C) 3934 // (sext x) == C --> x == (trunc C) 3935 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3936 DCI.isBeforeLegalize() && N0->hasOneUse()) { 3937 unsigned MinBits = N0.getValueSizeInBits(); 3938 SDValue PreExt; 3939 bool Signed = false; 3940 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 3941 // ZExt 3942 MinBits = N0->getOperand(0).getValueSizeInBits(); 3943 PreExt = N0->getOperand(0); 3944 } else if (N0->getOpcode() == ISD::AND) { 3945 // DAGCombine turns costly ZExts into ANDs 3946 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 3947 if ((C->getAPIntValue()+1).isPowerOf2()) { 3948 MinBits = C->getAPIntValue().countTrailingOnes(); 3949 PreExt = N0->getOperand(0); 3950 } 3951 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 3952 // SExt 3953 MinBits = N0->getOperand(0).getValueSizeInBits(); 3954 PreExt = N0->getOperand(0); 3955 Signed = true; 3956 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 3957 // ZEXTLOAD / SEXTLOAD 3958 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 3959 MinBits = LN0->getMemoryVT().getSizeInBits(); 3960 PreExt = N0; 3961 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 3962 Signed = true; 3963 MinBits = LN0->getMemoryVT().getSizeInBits(); 3964 PreExt = N0; 3965 } 3966 } 3967 3968 // Figure out how many bits we need to preserve this constant. 3969 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 3970 3971 // Make sure we're not losing bits from the constant. 3972 if (MinBits > 0 && 3973 MinBits < C1.getBitWidth() && 3974 MinBits >= ReqdBits) { 3975 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 3976 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 3977 // Will get folded away. 3978 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 3979 if (MinBits == 1 && C1 == 1) 3980 // Invert the condition. 3981 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 3982 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3983 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 3984 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 3985 } 3986 3987 // If truncating the setcc operands is not desirable, we can still 3988 // simplify the expression in some cases: 3989 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 3990 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 3991 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 3992 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 3993 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 3994 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 3995 SDValue TopSetCC = N0->getOperand(0); 3996 unsigned N0Opc = N0->getOpcode(); 3997 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 3998 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 3999 TopSetCC.getOpcode() == ISD::SETCC && 4000 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4001 (isConstFalseVal(N1) || 4002 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4003 4004 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4005 (!N1C->isZero() && Cond == ISD::SETNE); 4006 4007 if (!Inverse) 4008 return TopSetCC; 4009 4010 ISD::CondCode InvCond = ISD::getSetCCInverse( 4011 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4012 TopSetCC.getOperand(0).getValueType()); 4013 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4014 TopSetCC.getOperand(1), 4015 InvCond); 4016 } 4017 } 4018 } 4019 4020 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4021 // equality or unsigned, and all 1 bits of the const are in the same 4022 // partial word, see if we can shorten the load. 4023 if (DCI.isBeforeLegalize() && 4024 !ISD::isSignedIntSetCC(Cond) && 4025 N0.getOpcode() == ISD::AND && C1 == 0 && 4026 N0.getNode()->hasOneUse() && 4027 isa<LoadSDNode>(N0.getOperand(0)) && 4028 N0.getOperand(0).getNode()->hasOneUse() && 4029 isa<ConstantSDNode>(N0.getOperand(1))) { 4030 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4031 APInt bestMask; 4032 unsigned bestWidth = 0, bestOffset = 0; 4033 if (Lod->isSimple() && Lod->isUnindexed()) { 4034 unsigned origWidth = N0.getValueSizeInBits(); 4035 unsigned maskWidth = origWidth; 4036 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4037 // 8 bits, but have to be careful... 4038 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4039 origWidth = Lod->getMemoryVT().getSizeInBits(); 4040 const APInt &Mask = N0.getConstantOperandAPInt(1); 4041 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4042 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4043 for (unsigned offset=0; offset<origWidth/width; offset++) { 4044 if (Mask.isSubsetOf(newMask)) { 4045 if (Layout.isLittleEndian()) 4046 bestOffset = (uint64_t)offset * (width/8); 4047 else 4048 bestOffset = (origWidth/width - offset - 1) * (width/8); 4049 bestMask = Mask.lshr(offset * (width/8) * 8); 4050 bestWidth = width; 4051 break; 4052 } 4053 newMask <<= width; 4054 } 4055 } 4056 } 4057 if (bestWidth) { 4058 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4059 if (newVT.isRound() && 4060 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4061 SDValue Ptr = Lod->getBasePtr(); 4062 if (bestOffset != 0) 4063 Ptr = 4064 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4065 SDValue NewLoad = 4066 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4067 Lod->getPointerInfo().getWithOffset(bestOffset), 4068 Lod->getOriginalAlign()); 4069 return DAG.getSetCC(dl, VT, 4070 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4071 DAG.getConstant(bestMask.trunc(bestWidth), 4072 dl, newVT)), 4073 DAG.getConstant(0LL, dl, newVT), Cond); 4074 } 4075 } 4076 } 4077 4078 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4079 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4080 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4081 4082 // If the comparison constant has bits in the upper part, the 4083 // zero-extended value could never match. 4084 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4085 C1.getBitWidth() - InSize))) { 4086 switch (Cond) { 4087 case ISD::SETUGT: 4088 case ISD::SETUGE: 4089 case ISD::SETEQ: 4090 return DAG.getConstant(0, dl, VT); 4091 case ISD::SETULT: 4092 case ISD::SETULE: 4093 case ISD::SETNE: 4094 return DAG.getConstant(1, dl, VT); 4095 case ISD::SETGT: 4096 case ISD::SETGE: 4097 // True if the sign bit of C1 is set. 4098 return DAG.getConstant(C1.isNegative(), dl, VT); 4099 case ISD::SETLT: 4100 case ISD::SETLE: 4101 // True if the sign bit of C1 isn't set. 4102 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4103 default: 4104 break; 4105 } 4106 } 4107 4108 // Otherwise, we can perform the comparison with the low bits. 4109 switch (Cond) { 4110 case ISD::SETEQ: 4111 case ISD::SETNE: 4112 case ISD::SETUGT: 4113 case ISD::SETUGE: 4114 case ISD::SETULT: 4115 case ISD::SETULE: { 4116 EVT newVT = N0.getOperand(0).getValueType(); 4117 if (DCI.isBeforeLegalizeOps() || 4118 (isOperationLegal(ISD::SETCC, newVT) && 4119 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4120 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4121 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4122 4123 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4124 NewConst, Cond); 4125 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4126 } 4127 break; 4128 } 4129 default: 4130 break; // todo, be more careful with signed comparisons 4131 } 4132 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4133 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4134 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4135 OpVT)) { 4136 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4137 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4138 EVT ExtDstTy = N0.getValueType(); 4139 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4140 4141 // If the constant doesn't fit into the number of bits for the source of 4142 // the sign extension, it is impossible for both sides to be equal. 4143 if (C1.getMinSignedBits() > ExtSrcTyBits) 4144 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4145 4146 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4147 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4148 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4149 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4150 DAG.getConstant(Imm, dl, ExtDstTy)); 4151 if (!DCI.isCalledByLegalizer()) 4152 DCI.AddToWorklist(ZextOp.getNode()); 4153 // Otherwise, make this a use of a zext. 4154 return DAG.getSetCC(dl, VT, ZextOp, 4155 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4156 } else if ((N1C->isZero() || N1C->isOne()) && 4157 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4158 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4159 if (N0.getOpcode() == ISD::SETCC && 4160 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4161 (N0.getValueType() == MVT::i1 || 4162 getBooleanContents(N0.getOperand(0).getValueType()) == 4163 ZeroOrOneBooleanContent)) { 4164 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4165 if (TrueWhenTrue) 4166 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4167 // Invert the condition. 4168 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4169 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4170 if (DCI.isBeforeLegalizeOps() || 4171 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4172 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4173 } 4174 4175 if ((N0.getOpcode() == ISD::XOR || 4176 (N0.getOpcode() == ISD::AND && 4177 N0.getOperand(0).getOpcode() == ISD::XOR && 4178 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4179 isOneConstant(N0.getOperand(1))) { 4180 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4181 // can only do this if the top bits are known zero. 4182 unsigned BitWidth = N0.getValueSizeInBits(); 4183 if (DAG.MaskedValueIsZero(N0, 4184 APInt::getHighBitsSet(BitWidth, 4185 BitWidth-1))) { 4186 // Okay, get the un-inverted input value. 4187 SDValue Val; 4188 if (N0.getOpcode() == ISD::XOR) { 4189 Val = N0.getOperand(0); 4190 } else { 4191 assert(N0.getOpcode() == ISD::AND && 4192 N0.getOperand(0).getOpcode() == ISD::XOR); 4193 // ((X^1)&1)^1 -> X & 1 4194 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4195 N0.getOperand(0).getOperand(0), 4196 N0.getOperand(1)); 4197 } 4198 4199 return DAG.getSetCC(dl, VT, Val, N1, 4200 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4201 } 4202 } else if (N1C->isOne()) { 4203 SDValue Op0 = N0; 4204 if (Op0.getOpcode() == ISD::TRUNCATE) 4205 Op0 = Op0.getOperand(0); 4206 4207 if ((Op0.getOpcode() == ISD::XOR) && 4208 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4209 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4210 SDValue XorLHS = Op0.getOperand(0); 4211 SDValue XorRHS = Op0.getOperand(1); 4212 // Ensure that the input setccs return an i1 type or 0/1 value. 4213 if (Op0.getValueType() == MVT::i1 || 4214 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4215 ZeroOrOneBooleanContent && 4216 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4217 ZeroOrOneBooleanContent)) { 4218 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4219 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4220 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4221 } 4222 } 4223 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4224 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4225 if (Op0.getValueType().bitsGT(VT)) 4226 Op0 = DAG.getNode(ISD::AND, dl, VT, 4227 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4228 DAG.getConstant(1, dl, VT)); 4229 else if (Op0.getValueType().bitsLT(VT)) 4230 Op0 = DAG.getNode(ISD::AND, dl, VT, 4231 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4232 DAG.getConstant(1, dl, VT)); 4233 4234 return DAG.getSetCC(dl, VT, Op0, 4235 DAG.getConstant(0, dl, Op0.getValueType()), 4236 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4237 } 4238 if (Op0.getOpcode() == ISD::AssertZext && 4239 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4240 return DAG.getSetCC(dl, VT, Op0, 4241 DAG.getConstant(0, dl, Op0.getValueType()), 4242 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4243 } 4244 } 4245 4246 // Given: 4247 // icmp eq/ne (urem %x, %y), 0 4248 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4249 // icmp eq/ne %x, 0 4250 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4251 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4252 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4253 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4254 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4255 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4256 } 4257 4258 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4259 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4260 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4261 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4262 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4263 N1C && N1C->isAllOnes()) { 4264 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4265 DAG.getConstant(0, dl, OpVT), 4266 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4267 } 4268 4269 if (SDValue V = 4270 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4271 return V; 4272 } 4273 4274 // These simplifications apply to splat vectors as well. 4275 // TODO: Handle more splat vector cases. 4276 if (auto *N1C = isConstOrConstSplat(N1)) { 4277 const APInt &C1 = N1C->getAPIntValue(); 4278 4279 APInt MinVal, MaxVal; 4280 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4281 if (ISD::isSignedIntSetCC(Cond)) { 4282 MinVal = APInt::getSignedMinValue(OperandBitSize); 4283 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4284 } else { 4285 MinVal = APInt::getMinValue(OperandBitSize); 4286 MaxVal = APInt::getMaxValue(OperandBitSize); 4287 } 4288 4289 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4290 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4291 // X >= MIN --> true 4292 if (C1 == MinVal) 4293 return DAG.getBoolConstant(true, dl, VT, OpVT); 4294 4295 if (!VT.isVector()) { // TODO: Support this for vectors. 4296 // X >= C0 --> X > (C0 - 1) 4297 APInt C = C1 - 1; 4298 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4299 if ((DCI.isBeforeLegalizeOps() || 4300 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4301 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4302 isLegalICmpImmediate(C.getSExtValue())))) { 4303 return DAG.getSetCC(dl, VT, N0, 4304 DAG.getConstant(C, dl, N1.getValueType()), 4305 NewCC); 4306 } 4307 } 4308 } 4309 4310 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4311 // X <= MAX --> true 4312 if (C1 == MaxVal) 4313 return DAG.getBoolConstant(true, dl, VT, OpVT); 4314 4315 // X <= C0 --> X < (C0 + 1) 4316 if (!VT.isVector()) { // TODO: Support this for vectors. 4317 APInt C = C1 + 1; 4318 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4319 if ((DCI.isBeforeLegalizeOps() || 4320 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4321 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4322 isLegalICmpImmediate(C.getSExtValue())))) { 4323 return DAG.getSetCC(dl, VT, N0, 4324 DAG.getConstant(C, dl, N1.getValueType()), 4325 NewCC); 4326 } 4327 } 4328 } 4329 4330 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4331 if (C1 == MinVal) 4332 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4333 4334 // TODO: Support this for vectors after legalize ops. 4335 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4336 // Canonicalize setlt X, Max --> setne X, Max 4337 if (C1 == MaxVal) 4338 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4339 4340 // If we have setult X, 1, turn it into seteq X, 0 4341 if (C1 == MinVal+1) 4342 return DAG.getSetCC(dl, VT, N0, 4343 DAG.getConstant(MinVal, dl, N0.getValueType()), 4344 ISD::SETEQ); 4345 } 4346 } 4347 4348 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4349 if (C1 == MaxVal) 4350 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4351 4352 // TODO: Support this for vectors after legalize ops. 4353 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4354 // Canonicalize setgt X, Min --> setne X, Min 4355 if (C1 == MinVal) 4356 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4357 4358 // If we have setugt X, Max-1, turn it into seteq X, Max 4359 if (C1 == MaxVal-1) 4360 return DAG.getSetCC(dl, VT, N0, 4361 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4362 ISD::SETEQ); 4363 } 4364 } 4365 4366 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4367 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4368 if (C1.isZero()) 4369 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4370 VT, N0, N1, Cond, DCI, dl)) 4371 return CC; 4372 4373 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4374 // For example, when high 32-bits of i64 X are known clear: 4375 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4376 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4377 bool CmpZero = N1C->getAPIntValue().isZero(); 4378 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4379 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4380 // Match or(lo,shl(hi,bw/2)) pattern. 4381 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4382 unsigned EltBits = V.getScalarValueSizeInBits(); 4383 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4384 return false; 4385 SDValue LHS = V.getOperand(0); 4386 SDValue RHS = V.getOperand(1); 4387 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4388 // Unshifted element must have zero upperbits. 4389 if (RHS.getOpcode() == ISD::SHL && 4390 isa<ConstantSDNode>(RHS.getOperand(1)) && 4391 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4392 DAG.MaskedValueIsZero(LHS, HiBits)) { 4393 Lo = LHS; 4394 Hi = RHS.getOperand(0); 4395 return true; 4396 } 4397 if (LHS.getOpcode() == ISD::SHL && 4398 isa<ConstantSDNode>(LHS.getOperand(1)) && 4399 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4400 DAG.MaskedValueIsZero(RHS, HiBits)) { 4401 Lo = RHS; 4402 Hi = LHS.getOperand(0); 4403 return true; 4404 } 4405 return false; 4406 }; 4407 4408 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4409 unsigned EltBits = N0.getScalarValueSizeInBits(); 4410 unsigned HalfBits = EltBits / 2; 4411 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4412 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4413 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4414 SDValue NewN0 = 4415 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4416 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4417 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4418 }; 4419 4420 SDValue Lo, Hi; 4421 if (IsConcat(N0, Lo, Hi)) 4422 return MergeConcat(Lo, Hi); 4423 4424 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4425 SDValue Lo0, Lo1, Hi0, Hi1; 4426 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4427 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4428 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4429 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4430 } 4431 } 4432 } 4433 } 4434 4435 // If we have "setcc X, C0", check to see if we can shrink the immediate 4436 // by changing cc. 4437 // TODO: Support this for vectors after legalize ops. 4438 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4439 // SETUGT X, SINTMAX -> SETLT X, 0 4440 // SETUGE X, SINTMIN -> SETLT X, 0 4441 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4442 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4443 return DAG.getSetCC(dl, VT, N0, 4444 DAG.getConstant(0, dl, N1.getValueType()), 4445 ISD::SETLT); 4446 4447 // SETULT X, SINTMIN -> SETGT X, -1 4448 // SETULE X, SINTMAX -> SETGT X, -1 4449 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4450 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4451 return DAG.getSetCC(dl, VT, N0, 4452 DAG.getAllOnesConstant(dl, N1.getValueType()), 4453 ISD::SETGT); 4454 } 4455 } 4456 4457 // Back to non-vector simplifications. 4458 // TODO: Can we do these for vector splats? 4459 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4460 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4461 const APInt &C1 = N1C->getAPIntValue(); 4462 EVT ShValTy = N0.getValueType(); 4463 4464 // Fold bit comparisons when we can. This will result in an 4465 // incorrect value when boolean false is negative one, unless 4466 // the bitsize is 1 in which case the false value is the same 4467 // in practice regardless of the representation. 4468 if ((VT.getSizeInBits() == 1 || 4469 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4470 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4471 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4472 N0.getOpcode() == ISD::AND) { 4473 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4474 EVT ShiftTy = 4475 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4476 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4477 // Perform the xform if the AND RHS is a single bit. 4478 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4479 if (AndRHS->getAPIntValue().isPowerOf2() && 4480 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4481 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4482 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4483 DAG.getConstant(ShCt, dl, ShiftTy))); 4484 } 4485 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4486 // (X & 8) == 8 --> (X & 8) >> 3 4487 // Perform the xform if C1 is a single bit. 4488 unsigned ShCt = C1.logBase2(); 4489 if (C1.isPowerOf2() && 4490 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4491 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4492 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4493 DAG.getConstant(ShCt, dl, ShiftTy))); 4494 } 4495 } 4496 } 4497 } 4498 4499 if (C1.getMinSignedBits() <= 64 && 4500 !isLegalICmpImmediate(C1.getSExtValue())) { 4501 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4502 // (X & -256) == 256 -> (X >> 8) == 1 4503 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4504 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4505 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4506 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4507 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4508 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4509 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4510 SDValue Shift = 4511 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4512 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4513 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4514 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4515 } 4516 } 4517 } 4518 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4519 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4520 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4521 // X < 0x100000000 -> (X >> 32) < 1 4522 // X >= 0x100000000 -> (X >> 32) >= 1 4523 // X <= 0x0ffffffff -> (X >> 32) < 1 4524 // X > 0x0ffffffff -> (X >> 32) >= 1 4525 unsigned ShiftBits; 4526 APInt NewC = C1; 4527 ISD::CondCode NewCond = Cond; 4528 if (AdjOne) { 4529 ShiftBits = C1.countTrailingOnes(); 4530 NewC = NewC + 1; 4531 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4532 } else { 4533 ShiftBits = C1.countTrailingZeros(); 4534 } 4535 NewC.lshrInPlace(ShiftBits); 4536 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4537 isLegalICmpImmediate(NewC.getSExtValue()) && 4538 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4539 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4540 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4541 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4542 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4543 } 4544 } 4545 } 4546 } 4547 4548 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4549 auto *CFP = cast<ConstantFPSDNode>(N1); 4550 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4551 4552 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4553 // constant if knowing that the operand is non-nan is enough. We prefer to 4554 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4555 // materialize 0.0. 4556 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4557 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4558 4559 // setcc (fneg x), C -> setcc swap(pred) x, -C 4560 if (N0.getOpcode() == ISD::FNEG) { 4561 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4562 if (DCI.isBeforeLegalizeOps() || 4563 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4564 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4565 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4566 } 4567 } 4568 4569 // If the condition is not legal, see if we can find an equivalent one 4570 // which is legal. 4571 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4572 // If the comparison was an awkward floating-point == or != and one of 4573 // the comparison operands is infinity or negative infinity, convert the 4574 // condition to a less-awkward <= or >=. 4575 if (CFP->getValueAPF().isInfinity()) { 4576 bool IsNegInf = CFP->getValueAPF().isNegative(); 4577 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4578 switch (Cond) { 4579 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4580 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4581 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4582 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4583 default: break; 4584 } 4585 if (NewCond != ISD::SETCC_INVALID && 4586 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4587 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4588 } 4589 } 4590 } 4591 4592 if (N0 == N1) { 4593 // The sext(setcc()) => setcc() optimization relies on the appropriate 4594 // constant being emitted. 4595 assert(!N0.getValueType().isInteger() && 4596 "Integer types should be handled by FoldSetCC"); 4597 4598 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4599 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4600 if (UOF == 2) // FP operators that are undefined on NaNs. 4601 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4602 if (UOF == unsigned(EqTrue)) 4603 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4604 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4605 // if it is not already. 4606 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4607 if (NewCond != Cond && 4608 (DCI.isBeforeLegalizeOps() || 4609 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4610 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4611 } 4612 4613 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4614 N0.getValueType().isInteger()) { 4615 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4616 N0.getOpcode() == ISD::XOR) { 4617 // Simplify (X+Y) == (X+Z) --> Y == Z 4618 if (N0.getOpcode() == N1.getOpcode()) { 4619 if (N0.getOperand(0) == N1.getOperand(0)) 4620 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4621 if (N0.getOperand(1) == N1.getOperand(1)) 4622 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4623 if (isCommutativeBinOp(N0.getOpcode())) { 4624 // If X op Y == Y op X, try other combinations. 4625 if (N0.getOperand(0) == N1.getOperand(1)) 4626 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4627 Cond); 4628 if (N0.getOperand(1) == N1.getOperand(0)) 4629 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4630 Cond); 4631 } 4632 } 4633 4634 // If RHS is a legal immediate value for a compare instruction, we need 4635 // to be careful about increasing register pressure needlessly. 4636 bool LegalRHSImm = false; 4637 4638 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4639 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4640 // Turn (X+C1) == C2 --> X == C2-C1 4641 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 4642 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4643 DAG.getConstant(RHSC->getAPIntValue()- 4644 LHSR->getAPIntValue(), 4645 dl, N0.getValueType()), Cond); 4646 } 4647 4648 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 4649 if (N0.getOpcode() == ISD::XOR) 4650 // If we know that all of the inverted bits are zero, don't bother 4651 // performing the inversion. 4652 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 4653 return 4654 DAG.getSetCC(dl, VT, N0.getOperand(0), 4655 DAG.getConstant(LHSR->getAPIntValue() ^ 4656 RHSC->getAPIntValue(), 4657 dl, N0.getValueType()), 4658 Cond); 4659 } 4660 4661 // Turn (C1-X) == C2 --> X == C1-C2 4662 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 4663 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 4664 return 4665 DAG.getSetCC(dl, VT, N0.getOperand(1), 4666 DAG.getConstant(SUBC->getAPIntValue() - 4667 RHSC->getAPIntValue(), 4668 dl, N0.getValueType()), 4669 Cond); 4670 } 4671 } 4672 4673 // Could RHSC fold directly into a compare? 4674 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4675 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4676 } 4677 4678 // (X+Y) == X --> Y == 0 and similar folds. 4679 // Don't do this if X is an immediate that can fold into a cmp 4680 // instruction and X+Y has other uses. It could be an induction variable 4681 // chain, and the transform would increase register pressure. 4682 if (!LegalRHSImm || N0.hasOneUse()) 4683 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4684 return V; 4685 } 4686 4687 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4688 N1.getOpcode() == ISD::XOR) 4689 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4690 return V; 4691 4692 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4693 return V; 4694 } 4695 4696 // Fold remainder of division by a constant. 4697 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4698 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4699 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4700 4701 // When division is cheap or optimizing for minimum size, 4702 // fall through to DIVREM creation by skipping this fold. 4703 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4704 if (N0.getOpcode() == ISD::UREM) { 4705 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4706 return Folded; 4707 } else if (N0.getOpcode() == ISD::SREM) { 4708 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4709 return Folded; 4710 } 4711 } 4712 } 4713 4714 // Fold away ALL boolean setcc's. 4715 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4716 SDValue Temp; 4717 switch (Cond) { 4718 default: llvm_unreachable("Unknown integer setcc!"); 4719 case ISD::SETEQ: // X == Y -> ~(X^Y) 4720 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4721 N0 = DAG.getNOT(dl, Temp, OpVT); 4722 if (!DCI.isCalledByLegalizer()) 4723 DCI.AddToWorklist(Temp.getNode()); 4724 break; 4725 case ISD::SETNE: // X != Y --> (X^Y) 4726 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4727 break; 4728 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4729 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4730 Temp = DAG.getNOT(dl, N0, OpVT); 4731 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4732 if (!DCI.isCalledByLegalizer()) 4733 DCI.AddToWorklist(Temp.getNode()); 4734 break; 4735 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4736 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4737 Temp = DAG.getNOT(dl, N1, OpVT); 4738 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4739 if (!DCI.isCalledByLegalizer()) 4740 DCI.AddToWorklist(Temp.getNode()); 4741 break; 4742 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4743 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4744 Temp = DAG.getNOT(dl, N0, OpVT); 4745 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4746 if (!DCI.isCalledByLegalizer()) 4747 DCI.AddToWorklist(Temp.getNode()); 4748 break; 4749 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4750 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4751 Temp = DAG.getNOT(dl, N1, OpVT); 4752 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4753 break; 4754 } 4755 if (VT.getScalarType() != MVT::i1) { 4756 if (!DCI.isCalledByLegalizer()) 4757 DCI.AddToWorklist(N0.getNode()); 4758 // FIXME: If running after legalize, we probably can't do this. 4759 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4760 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4761 } 4762 return N0; 4763 } 4764 4765 // Could not fold it. 4766 return SDValue(); 4767 } 4768 4769 /// Returns true (and the GlobalValue and the offset) if the node is a 4770 /// GlobalAddress + offset. 4771 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4772 int64_t &Offset) const { 4773 4774 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4775 4776 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4777 GA = GASD->getGlobal(); 4778 Offset += GASD->getOffset(); 4779 return true; 4780 } 4781 4782 if (N->getOpcode() == ISD::ADD) { 4783 SDValue N1 = N->getOperand(0); 4784 SDValue N2 = N->getOperand(1); 4785 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4786 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4787 Offset += V->getSExtValue(); 4788 return true; 4789 } 4790 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4791 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4792 Offset += V->getSExtValue(); 4793 return true; 4794 } 4795 } 4796 } 4797 4798 return false; 4799 } 4800 4801 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4802 DAGCombinerInfo &DCI) const { 4803 // Default implementation: no optimization. 4804 return SDValue(); 4805 } 4806 4807 //===----------------------------------------------------------------------===// 4808 // Inline Assembler Implementation Methods 4809 //===----------------------------------------------------------------------===// 4810 4811 TargetLowering::ConstraintType 4812 TargetLowering::getConstraintType(StringRef Constraint) const { 4813 unsigned S = Constraint.size(); 4814 4815 if (S == 1) { 4816 switch (Constraint[0]) { 4817 default: break; 4818 case 'r': 4819 return C_RegisterClass; 4820 case 'm': // memory 4821 case 'o': // offsetable 4822 case 'V': // not offsetable 4823 return C_Memory; 4824 case 'n': // Simple Integer 4825 case 'E': // Floating Point Constant 4826 case 'F': // Floating Point Constant 4827 return C_Immediate; 4828 case 'i': // Simple Integer or Relocatable Constant 4829 case 's': // Relocatable Constant 4830 case 'p': // Address. 4831 case 'X': // Allow ANY value. 4832 case 'I': // Target registers. 4833 case 'J': 4834 case 'K': 4835 case 'L': 4836 case 'M': 4837 case 'N': 4838 case 'O': 4839 case 'P': 4840 case '<': 4841 case '>': 4842 return C_Other; 4843 } 4844 } 4845 4846 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4847 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4848 return C_Memory; 4849 return C_Register; 4850 } 4851 return C_Unknown; 4852 } 4853 4854 /// Try to replace an X constraint, which matches anything, with another that 4855 /// has more specific requirements based on the type of the corresponding 4856 /// operand. 4857 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4858 if (ConstraintVT.isInteger()) 4859 return "r"; 4860 if (ConstraintVT.isFloatingPoint()) 4861 return "f"; // works for many targets 4862 return nullptr; 4863 } 4864 4865 SDValue TargetLowering::LowerAsmOutputForConstraint( 4866 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4867 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4868 return SDValue(); 4869 } 4870 4871 /// Lower the specified operand into the Ops vector. 4872 /// If it is invalid, don't add anything to Ops. 4873 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4874 std::string &Constraint, 4875 std::vector<SDValue> &Ops, 4876 SelectionDAG &DAG) const { 4877 4878 if (Constraint.length() > 1) return; 4879 4880 char ConstraintLetter = Constraint[0]; 4881 switch (ConstraintLetter) { 4882 default: break; 4883 case 'X': // Allows any operand 4884 case 'i': // Simple Integer or Relocatable Constant 4885 case 'n': // Simple Integer 4886 case 's': { // Relocatable Constant 4887 4888 ConstantSDNode *C; 4889 uint64_t Offset = 0; 4890 4891 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 4892 // etc., since getelementpointer is variadic. We can't use 4893 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 4894 // while in this case the GA may be furthest from the root node which is 4895 // likely an ISD::ADD. 4896 while (true) { 4897 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 4898 // gcc prints these as sign extended. Sign extend value to 64 bits 4899 // now; without this it would get ZExt'd later in 4900 // ScheduleDAGSDNodes::EmitNode, which is very generic. 4901 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 4902 BooleanContent BCont = getBooleanContents(MVT::i64); 4903 ISD::NodeType ExtOpc = 4904 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 4905 int64_t ExtVal = 4906 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 4907 Ops.push_back( 4908 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 4909 return; 4910 } 4911 if (ConstraintLetter != 'n') { 4912 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 4913 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 4914 GA->getValueType(0), 4915 Offset + GA->getOffset())); 4916 return; 4917 } 4918 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 4919 Ops.push_back(DAG.getTargetBlockAddress( 4920 BA->getBlockAddress(), BA->getValueType(0), 4921 Offset + BA->getOffset(), BA->getTargetFlags())); 4922 return; 4923 } 4924 if (isa<BasicBlockSDNode>(Op)) { 4925 Ops.push_back(Op); 4926 return; 4927 } 4928 } 4929 const unsigned OpCode = Op.getOpcode(); 4930 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 4931 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 4932 Op = Op.getOperand(1); 4933 // Subtraction is not commutative. 4934 else if (OpCode == ISD::ADD && 4935 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 4936 Op = Op.getOperand(0); 4937 else 4938 return; 4939 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 4940 continue; 4941 } 4942 return; 4943 } 4944 break; 4945 } 4946 } 4947 } 4948 4949 std::pair<unsigned, const TargetRegisterClass *> 4950 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4951 StringRef Constraint, 4952 MVT VT) const { 4953 if (Constraint.empty() || Constraint[0] != '{') 4954 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4955 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4956 4957 // Remove the braces from around the name. 4958 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4959 4960 std::pair<unsigned, const TargetRegisterClass *> R = 4961 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4962 4963 // Figure out which register class contains this reg. 4964 for (const TargetRegisterClass *RC : RI->regclasses()) { 4965 // If none of the value types for this register class are valid, we 4966 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4967 if (!isLegalRC(*RI, *RC)) 4968 continue; 4969 4970 for (const MCPhysReg &PR : *RC) { 4971 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 4972 std::pair<unsigned, const TargetRegisterClass *> S = 4973 std::make_pair(PR, RC); 4974 4975 // If this register class has the requested value type, return it, 4976 // otherwise keep searching and return the first class found 4977 // if no other is found which explicitly has the requested type. 4978 if (RI->isTypeLegalForClass(*RC, VT)) 4979 return S; 4980 if (!R.second) 4981 R = S; 4982 } 4983 } 4984 } 4985 4986 return R; 4987 } 4988 4989 //===----------------------------------------------------------------------===// 4990 // Constraint Selection. 4991 4992 /// Return true of this is an input operand that is a matching constraint like 4993 /// "4". 4994 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4995 assert(!ConstraintCode.empty() && "No known constraint!"); 4996 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4997 } 4998 4999 /// If this is an input matching constraint, this method returns the output 5000 /// operand it matches. 5001 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5002 assert(!ConstraintCode.empty() && "No known constraint!"); 5003 return atoi(ConstraintCode.c_str()); 5004 } 5005 5006 /// Split up the constraint string from the inline assembly value into the 5007 /// specific constraints and their prefixes, and also tie in the associated 5008 /// operand values. 5009 /// If this returns an empty vector, and if the constraint string itself 5010 /// isn't empty, there was an error parsing. 5011 TargetLowering::AsmOperandInfoVector 5012 TargetLowering::ParseConstraints(const DataLayout &DL, 5013 const TargetRegisterInfo *TRI, 5014 const CallBase &Call) const { 5015 /// Information about all of the constraints. 5016 AsmOperandInfoVector ConstraintOperands; 5017 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5018 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5019 5020 // Do a prepass over the constraints, canonicalizing them, and building up the 5021 // ConstraintOperands list. 5022 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5023 unsigned ResNo = 0; // ResNo - The result number of the next output. 5024 5025 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5026 ConstraintOperands.emplace_back(std::move(CI)); 5027 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5028 5029 // Update multiple alternative constraint count. 5030 if (OpInfo.multipleAlternatives.size() > maCount) 5031 maCount = OpInfo.multipleAlternatives.size(); 5032 5033 OpInfo.ConstraintVT = MVT::Other; 5034 5035 // Compute the value type for each operand. 5036 switch (OpInfo.Type) { 5037 case InlineAsm::isOutput: 5038 // Indirect outputs just consume an argument. 5039 if (OpInfo.isIndirect) { 5040 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5041 break; 5042 } 5043 5044 // The return value of the call is this value. As such, there is no 5045 // corresponding argument. 5046 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5047 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5048 OpInfo.ConstraintVT = 5049 getSimpleValueType(DL, STy->getElementType(ResNo)); 5050 } else { 5051 assert(ResNo == 0 && "Asm only has one result!"); 5052 OpInfo.ConstraintVT = 5053 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5054 } 5055 ++ResNo; 5056 break; 5057 case InlineAsm::isInput: 5058 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5059 break; 5060 case InlineAsm::isClobber: 5061 // Nothing to do. 5062 break; 5063 } 5064 5065 if (OpInfo.CallOperandVal) { 5066 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5067 if (OpInfo.isIndirect) { 5068 OpTy = Call.getParamElementType(ArgNo); 5069 assert(OpTy && "Indirect operand must have elementtype attribute"); 5070 } 5071 5072 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5073 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5074 if (STy->getNumElements() == 1) 5075 OpTy = STy->getElementType(0); 5076 5077 // If OpTy is not a single value, it may be a struct/union that we 5078 // can tile with integers. 5079 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5080 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5081 switch (BitSize) { 5082 default: break; 5083 case 1: 5084 case 8: 5085 case 16: 5086 case 32: 5087 case 64: 5088 case 128: 5089 OpInfo.ConstraintVT = 5090 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 5091 break; 5092 } 5093 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 5094 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 5095 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 5096 } else { 5097 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 5098 } 5099 5100 ArgNo++; 5101 } 5102 } 5103 5104 // If we have multiple alternative constraints, select the best alternative. 5105 if (!ConstraintOperands.empty()) { 5106 if (maCount) { 5107 unsigned bestMAIndex = 0; 5108 int bestWeight = -1; 5109 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5110 int weight = -1; 5111 unsigned maIndex; 5112 // Compute the sums of the weights for each alternative, keeping track 5113 // of the best (highest weight) one so far. 5114 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5115 int weightSum = 0; 5116 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5117 cIndex != eIndex; ++cIndex) { 5118 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5119 if (OpInfo.Type == InlineAsm::isClobber) 5120 continue; 5121 5122 // If this is an output operand with a matching input operand, 5123 // look up the matching input. If their types mismatch, e.g. one 5124 // is an integer, the other is floating point, or their sizes are 5125 // different, flag it as an maCantMatch. 5126 if (OpInfo.hasMatchingInput()) { 5127 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5128 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5129 if ((OpInfo.ConstraintVT.isInteger() != 5130 Input.ConstraintVT.isInteger()) || 5131 (OpInfo.ConstraintVT.getSizeInBits() != 5132 Input.ConstraintVT.getSizeInBits())) { 5133 weightSum = -1; // Can't match. 5134 break; 5135 } 5136 } 5137 } 5138 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5139 if (weight == -1) { 5140 weightSum = -1; 5141 break; 5142 } 5143 weightSum += weight; 5144 } 5145 // Update best. 5146 if (weightSum > bestWeight) { 5147 bestWeight = weightSum; 5148 bestMAIndex = maIndex; 5149 } 5150 } 5151 5152 // Now select chosen alternative in each constraint. 5153 for (AsmOperandInfo &cInfo : ConstraintOperands) 5154 if (cInfo.Type != InlineAsm::isClobber) 5155 cInfo.selectAlternative(bestMAIndex); 5156 } 5157 } 5158 5159 // Check and hook up tied operands, choose constraint code to use. 5160 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5161 cIndex != eIndex; ++cIndex) { 5162 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5163 5164 // If this is an output operand with a matching input operand, look up the 5165 // matching input. If their types mismatch, e.g. one is an integer, the 5166 // other is floating point, or their sizes are different, flag it as an 5167 // error. 5168 if (OpInfo.hasMatchingInput()) { 5169 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5170 5171 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5172 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5173 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5174 OpInfo.ConstraintVT); 5175 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5176 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5177 Input.ConstraintVT); 5178 if ((OpInfo.ConstraintVT.isInteger() != 5179 Input.ConstraintVT.isInteger()) || 5180 (MatchRC.second != InputRC.second)) { 5181 report_fatal_error("Unsupported asm: input constraint" 5182 " with a matching output constraint of" 5183 " incompatible type!"); 5184 } 5185 } 5186 } 5187 } 5188 5189 return ConstraintOperands; 5190 } 5191 5192 /// Return an integer indicating how general CT is. 5193 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5194 switch (CT) { 5195 case TargetLowering::C_Immediate: 5196 case TargetLowering::C_Other: 5197 case TargetLowering::C_Unknown: 5198 return 0; 5199 case TargetLowering::C_Register: 5200 return 1; 5201 case TargetLowering::C_RegisterClass: 5202 return 2; 5203 case TargetLowering::C_Memory: 5204 return 3; 5205 } 5206 llvm_unreachable("Invalid constraint type"); 5207 } 5208 5209 /// Examine constraint type and operand type and determine a weight value. 5210 /// This object must already have been set up with the operand type 5211 /// and the current alternative constraint selected. 5212 TargetLowering::ConstraintWeight 5213 TargetLowering::getMultipleConstraintMatchWeight( 5214 AsmOperandInfo &info, int maIndex) const { 5215 InlineAsm::ConstraintCodeVector *rCodes; 5216 if (maIndex >= (int)info.multipleAlternatives.size()) 5217 rCodes = &info.Codes; 5218 else 5219 rCodes = &info.multipleAlternatives[maIndex].Codes; 5220 ConstraintWeight BestWeight = CW_Invalid; 5221 5222 // Loop over the options, keeping track of the most general one. 5223 for (const std::string &rCode : *rCodes) { 5224 ConstraintWeight weight = 5225 getSingleConstraintMatchWeight(info, rCode.c_str()); 5226 if (weight > BestWeight) 5227 BestWeight = weight; 5228 } 5229 5230 return BestWeight; 5231 } 5232 5233 /// Examine constraint type and operand type and determine a weight value. 5234 /// This object must already have been set up with the operand type 5235 /// and the current alternative constraint selected. 5236 TargetLowering::ConstraintWeight 5237 TargetLowering::getSingleConstraintMatchWeight( 5238 AsmOperandInfo &info, const char *constraint) const { 5239 ConstraintWeight weight = CW_Invalid; 5240 Value *CallOperandVal = info.CallOperandVal; 5241 // If we don't have a value, we can't do a match, 5242 // but allow it at the lowest weight. 5243 if (!CallOperandVal) 5244 return CW_Default; 5245 // Look at the constraint type. 5246 switch (*constraint) { 5247 case 'i': // immediate integer. 5248 case 'n': // immediate integer with a known value. 5249 if (isa<ConstantInt>(CallOperandVal)) 5250 weight = CW_Constant; 5251 break; 5252 case 's': // non-explicit intregal immediate. 5253 if (isa<GlobalValue>(CallOperandVal)) 5254 weight = CW_Constant; 5255 break; 5256 case 'E': // immediate float if host format. 5257 case 'F': // immediate float. 5258 if (isa<ConstantFP>(CallOperandVal)) 5259 weight = CW_Constant; 5260 break; 5261 case '<': // memory operand with autodecrement. 5262 case '>': // memory operand with autoincrement. 5263 case 'm': // memory operand. 5264 case 'o': // offsettable memory operand 5265 case 'V': // non-offsettable memory operand 5266 weight = CW_Memory; 5267 break; 5268 case 'r': // general register. 5269 case 'g': // general register, memory operand or immediate integer. 5270 // note: Clang converts "g" to "imr". 5271 if (CallOperandVal->getType()->isIntegerTy()) 5272 weight = CW_Register; 5273 break; 5274 case 'X': // any operand. 5275 default: 5276 weight = CW_Default; 5277 break; 5278 } 5279 return weight; 5280 } 5281 5282 /// If there are multiple different constraints that we could pick for this 5283 /// operand (e.g. "imr") try to pick the 'best' one. 5284 /// This is somewhat tricky: constraints fall into four classes: 5285 /// Other -> immediates and magic values 5286 /// Register -> one specific register 5287 /// RegisterClass -> a group of regs 5288 /// Memory -> memory 5289 /// Ideally, we would pick the most specific constraint possible: if we have 5290 /// something that fits into a register, we would pick it. The problem here 5291 /// is that if we have something that could either be in a register or in 5292 /// memory that use of the register could cause selection of *other* 5293 /// operands to fail: they might only succeed if we pick memory. Because of 5294 /// this the heuristic we use is: 5295 /// 5296 /// 1) If there is an 'other' constraint, and if the operand is valid for 5297 /// that constraint, use it. This makes us take advantage of 'i' 5298 /// constraints when available. 5299 /// 2) Otherwise, pick the most general constraint present. This prefers 5300 /// 'm' over 'r', for example. 5301 /// 5302 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5303 const TargetLowering &TLI, 5304 SDValue Op, SelectionDAG *DAG) { 5305 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5306 unsigned BestIdx = 0; 5307 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5308 int BestGenerality = -1; 5309 5310 // Loop over the options, keeping track of the most general one. 5311 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5312 TargetLowering::ConstraintType CType = 5313 TLI.getConstraintType(OpInfo.Codes[i]); 5314 5315 // Indirect 'other' or 'immediate' constraints are not allowed. 5316 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5317 CType == TargetLowering::C_Register || 5318 CType == TargetLowering::C_RegisterClass)) 5319 continue; 5320 5321 // If this is an 'other' or 'immediate' constraint, see if the operand is 5322 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5323 // the operand is an integer in the range [0..31] we want to use I (saving a 5324 // load of a register), otherwise we must use 'r'. 5325 if ((CType == TargetLowering::C_Other || 5326 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5327 assert(OpInfo.Codes[i].size() == 1 && 5328 "Unhandled multi-letter 'other' constraint"); 5329 std::vector<SDValue> ResultOps; 5330 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5331 ResultOps, *DAG); 5332 if (!ResultOps.empty()) { 5333 BestType = CType; 5334 BestIdx = i; 5335 break; 5336 } 5337 } 5338 5339 // Things with matching constraints can only be registers, per gcc 5340 // documentation. This mainly affects "g" constraints. 5341 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5342 continue; 5343 5344 // This constraint letter is more general than the previous one, use it. 5345 int Generality = getConstraintGenerality(CType); 5346 if (Generality > BestGenerality) { 5347 BestType = CType; 5348 BestIdx = i; 5349 BestGenerality = Generality; 5350 } 5351 } 5352 5353 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5354 OpInfo.ConstraintType = BestType; 5355 } 5356 5357 /// Determines the constraint code and constraint type to use for the specific 5358 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5359 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5360 SDValue Op, 5361 SelectionDAG *DAG) const { 5362 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5363 5364 // Single-letter constraints ('r') are very common. 5365 if (OpInfo.Codes.size() == 1) { 5366 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5367 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5368 } else { 5369 ChooseConstraint(OpInfo, *this, Op, DAG); 5370 } 5371 5372 // 'X' matches anything. 5373 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5374 // Constants are handled elsewhere. For Functions, the type here is the 5375 // type of the result, which is not what we want to look at; leave them 5376 // alone. 5377 Value *v = OpInfo.CallOperandVal; 5378 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5379 return; 5380 } 5381 5382 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5383 OpInfo.ConstraintCode = "i"; 5384 return; 5385 } 5386 5387 // Otherwise, try to resolve it to something we know about by looking at 5388 // the actual operand type. 5389 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5390 OpInfo.ConstraintCode = Repl; 5391 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5392 } 5393 } 5394 } 5395 5396 /// Given an exact SDIV by a constant, create a multiplication 5397 /// with the multiplicative inverse of the constant. 5398 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5399 const SDLoc &dl, SelectionDAG &DAG, 5400 SmallVectorImpl<SDNode *> &Created) { 5401 SDValue Op0 = N->getOperand(0); 5402 SDValue Op1 = N->getOperand(1); 5403 EVT VT = N->getValueType(0); 5404 EVT SVT = VT.getScalarType(); 5405 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5406 EVT ShSVT = ShVT.getScalarType(); 5407 5408 bool UseSRA = false; 5409 SmallVector<SDValue, 16> Shifts, Factors; 5410 5411 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5412 if (C->isZero()) 5413 return false; 5414 APInt Divisor = C->getAPIntValue(); 5415 unsigned Shift = Divisor.countTrailingZeros(); 5416 if (Shift) { 5417 Divisor.ashrInPlace(Shift); 5418 UseSRA = true; 5419 } 5420 // Calculate the multiplicative inverse, using Newton's method. 5421 APInt t; 5422 APInt Factor = Divisor; 5423 while ((t = Divisor * Factor) != 1) 5424 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5425 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5426 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5427 return true; 5428 }; 5429 5430 // Collect all magic values from the build vector. 5431 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5432 return SDValue(); 5433 5434 SDValue Shift, Factor; 5435 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5436 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5437 Factor = DAG.getBuildVector(VT, dl, Factors); 5438 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5439 assert(Shifts.size() == 1 && Factors.size() == 1 && 5440 "Expected matchUnaryPredicate to return one element for scalable " 5441 "vectors"); 5442 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5443 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5444 } else { 5445 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5446 Shift = Shifts[0]; 5447 Factor = Factors[0]; 5448 } 5449 5450 SDValue Res = Op0; 5451 5452 // Shift the value upfront if it is even, so the LSB is one. 5453 if (UseSRA) { 5454 // TODO: For UDIV use SRL instead of SRA. 5455 SDNodeFlags Flags; 5456 Flags.setExact(true); 5457 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5458 Created.push_back(Res.getNode()); 5459 } 5460 5461 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5462 } 5463 5464 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5465 SelectionDAG &DAG, 5466 SmallVectorImpl<SDNode *> &Created) const { 5467 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5469 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5470 return SDValue(N, 0); // Lower SDIV as SDIV 5471 return SDValue(); 5472 } 5473 5474 /// Given an ISD::SDIV node expressing a divide by constant, 5475 /// return a DAG expression to select that will generate the same value by 5476 /// multiplying by a magic number. 5477 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5478 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5479 bool IsAfterLegalization, 5480 SmallVectorImpl<SDNode *> &Created) const { 5481 SDLoc dl(N); 5482 EVT VT = N->getValueType(0); 5483 EVT SVT = VT.getScalarType(); 5484 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5485 EVT ShSVT = ShVT.getScalarType(); 5486 unsigned EltBits = VT.getScalarSizeInBits(); 5487 EVT MulVT; 5488 5489 // Check to see if we can do this. 5490 // FIXME: We should be more aggressive here. 5491 if (!isTypeLegal(VT)) { 5492 // Limit this to simple scalars for now. 5493 if (VT.isVector() || !VT.isSimple()) 5494 return SDValue(); 5495 5496 // If this type will be promoted to a large enough type with a legal 5497 // multiply operation, we can go ahead and do this transform. 5498 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5499 return SDValue(); 5500 5501 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5502 if (MulVT.getSizeInBits() < (2 * EltBits) || 5503 !isOperationLegal(ISD::MUL, MulVT)) 5504 return SDValue(); 5505 } 5506 5507 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5508 if (N->getFlags().hasExact()) 5509 return BuildExactSDIV(*this, N, dl, DAG, Created); 5510 5511 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5512 5513 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5514 if (C->isZero()) 5515 return false; 5516 5517 const APInt &Divisor = C->getAPIntValue(); 5518 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5519 int NumeratorFactor = 0; 5520 int ShiftMask = -1; 5521 5522 if (Divisor.isOne() || Divisor.isAllOnes()) { 5523 // If d is +1/-1, we just multiply the numerator by +1/-1. 5524 NumeratorFactor = Divisor.getSExtValue(); 5525 magics.Magic = 0; 5526 magics.ShiftAmount = 0; 5527 ShiftMask = 0; 5528 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5529 // If d > 0 and m < 0, add the numerator. 5530 NumeratorFactor = 1; 5531 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5532 // If d < 0 and m > 0, subtract the numerator. 5533 NumeratorFactor = -1; 5534 } 5535 5536 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5537 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5538 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5539 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5540 return true; 5541 }; 5542 5543 SDValue N0 = N->getOperand(0); 5544 SDValue N1 = N->getOperand(1); 5545 5546 // Collect the shifts / magic values from each element. 5547 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5548 return SDValue(); 5549 5550 SDValue MagicFactor, Factor, Shift, ShiftMask; 5551 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5552 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5553 Factor = DAG.getBuildVector(VT, dl, Factors); 5554 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5555 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5556 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5557 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5558 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5559 "Expected matchUnaryPredicate to return one element for scalable " 5560 "vectors"); 5561 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5562 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5563 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5564 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5565 } else { 5566 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5567 MagicFactor = MagicFactors[0]; 5568 Factor = Factors[0]; 5569 Shift = Shifts[0]; 5570 ShiftMask = ShiftMasks[0]; 5571 } 5572 5573 // Multiply the numerator (operand 0) by the magic value. 5574 // FIXME: We should support doing a MUL in a wider type. 5575 auto GetMULHS = [&](SDValue X, SDValue Y) { 5576 // If the type isn't legal, use a wider mul of the the type calculated 5577 // earlier. 5578 if (!isTypeLegal(VT)) { 5579 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5580 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5581 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5582 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5583 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5584 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5585 } 5586 5587 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5588 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5589 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5590 SDValue LoHi = 5591 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5592 return SDValue(LoHi.getNode(), 1); 5593 } 5594 return SDValue(); 5595 }; 5596 5597 SDValue Q = GetMULHS(N0, MagicFactor); 5598 if (!Q) 5599 return SDValue(); 5600 5601 Created.push_back(Q.getNode()); 5602 5603 // (Optionally) Add/subtract the numerator using Factor. 5604 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5605 Created.push_back(Factor.getNode()); 5606 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5607 Created.push_back(Q.getNode()); 5608 5609 // Shift right algebraic by shift value. 5610 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5611 Created.push_back(Q.getNode()); 5612 5613 // Extract the sign bit, mask it and add it to the quotient. 5614 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5615 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5616 Created.push_back(T.getNode()); 5617 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5618 Created.push_back(T.getNode()); 5619 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5620 } 5621 5622 /// Given an ISD::UDIV node expressing a divide by constant, 5623 /// return a DAG expression to select that will generate the same value by 5624 /// multiplying by a magic number. 5625 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5626 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5627 bool IsAfterLegalization, 5628 SmallVectorImpl<SDNode *> &Created) const { 5629 SDLoc dl(N); 5630 EVT VT = N->getValueType(0); 5631 EVT SVT = VT.getScalarType(); 5632 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5633 EVT ShSVT = ShVT.getScalarType(); 5634 unsigned EltBits = VT.getScalarSizeInBits(); 5635 EVT MulVT; 5636 5637 // Check to see if we can do this. 5638 // FIXME: We should be more aggressive here. 5639 if (!isTypeLegal(VT)) { 5640 // Limit this to simple scalars for now. 5641 if (VT.isVector() || !VT.isSimple()) 5642 return SDValue(); 5643 5644 // If this type will be promoted to a large enough type with a legal 5645 // multiply operation, we can go ahead and do this transform. 5646 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5647 return SDValue(); 5648 5649 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5650 if (MulVT.getSizeInBits() < (2 * EltBits) || 5651 !isOperationLegal(ISD::MUL, MulVT)) 5652 return SDValue(); 5653 } 5654 5655 bool UseNPQ = false; 5656 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5657 5658 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5659 if (C->isZero()) 5660 return false; 5661 // FIXME: We should use a narrower constant when the upper 5662 // bits are known to be zero. 5663 const APInt& Divisor = C->getAPIntValue(); 5664 UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor); 5665 unsigned PreShift = 0, PostShift = 0; 5666 5667 // If the divisor is even, we can avoid using the expensive fixup by 5668 // shifting the divided value upfront. 5669 if (magics.IsAdd != 0 && !Divisor[0]) { 5670 PreShift = Divisor.countTrailingZeros(); 5671 // Get magic number for the shifted divisor. 5672 magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5673 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 5674 } 5675 5676 APInt Magic = magics.Magic; 5677 5678 unsigned SelNPQ; 5679 if (magics.IsAdd == 0 || Divisor.isOne()) { 5680 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5681 "We shouldn't generate an undefined shift!"); 5682 PostShift = magics.ShiftAmount; 5683 SelNPQ = false; 5684 } else { 5685 PostShift = magics.ShiftAmount - 1; 5686 SelNPQ = true; 5687 } 5688 5689 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5690 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5691 NPQFactors.push_back( 5692 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5693 : APInt::getZero(EltBits), 5694 dl, SVT)); 5695 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5696 UseNPQ |= SelNPQ; 5697 return true; 5698 }; 5699 5700 SDValue N0 = N->getOperand(0); 5701 SDValue N1 = N->getOperand(1); 5702 5703 // Collect the shifts/magic values from each element. 5704 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5705 return SDValue(); 5706 5707 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5708 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5709 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5710 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5711 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5712 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5713 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5714 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5715 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5716 "Expected matchUnaryPredicate to return one for scalable vectors"); 5717 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5718 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5719 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5720 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5721 } else { 5722 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5723 PreShift = PreShifts[0]; 5724 MagicFactor = MagicFactors[0]; 5725 PostShift = PostShifts[0]; 5726 } 5727 5728 SDValue Q = N0; 5729 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5730 Created.push_back(Q.getNode()); 5731 5732 // FIXME: We should support doing a MUL in a wider type. 5733 auto GetMULHU = [&](SDValue X, SDValue Y) { 5734 // If the type isn't legal, use a wider mul of the the type calculated 5735 // earlier. 5736 if (!isTypeLegal(VT)) { 5737 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5738 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5739 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5740 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5741 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5742 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5743 } 5744 5745 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5746 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5747 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5748 SDValue LoHi = 5749 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5750 return SDValue(LoHi.getNode(), 1); 5751 } 5752 return SDValue(); // No mulhu or equivalent 5753 }; 5754 5755 // Multiply the numerator (operand 0) by the magic value. 5756 Q = GetMULHU(Q, MagicFactor); 5757 if (!Q) 5758 return SDValue(); 5759 5760 Created.push_back(Q.getNode()); 5761 5762 if (UseNPQ) { 5763 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5764 Created.push_back(NPQ.getNode()); 5765 5766 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5767 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5768 if (VT.isVector()) 5769 NPQ = GetMULHU(NPQ, NPQFactor); 5770 else 5771 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5772 5773 Created.push_back(NPQ.getNode()); 5774 5775 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5776 Created.push_back(Q.getNode()); 5777 } 5778 5779 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5780 Created.push_back(Q.getNode()); 5781 5782 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5783 5784 SDValue One = DAG.getConstant(1, dl, VT); 5785 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5786 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5787 } 5788 5789 /// If all values in Values that *don't* match the predicate are same 'splat' 5790 /// value, then replace all values with that splat value. 5791 /// Else, if AlternativeReplacement was provided, then replace all values that 5792 /// do match predicate with AlternativeReplacement value. 5793 static void 5794 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5795 std::function<bool(SDValue)> Predicate, 5796 SDValue AlternativeReplacement = SDValue()) { 5797 SDValue Replacement; 5798 // Is there a value for which the Predicate does *NOT* match? What is it? 5799 auto SplatValue = llvm::find_if_not(Values, Predicate); 5800 if (SplatValue != Values.end()) { 5801 // Does Values consist only of SplatValue's and values matching Predicate? 5802 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5803 return Value == *SplatValue || Predicate(Value); 5804 })) // Then we shall replace values matching predicate with SplatValue. 5805 Replacement = *SplatValue; 5806 } 5807 if (!Replacement) { 5808 // Oops, we did not find the "baseline" splat value. 5809 if (!AlternativeReplacement) 5810 return; // Nothing to do. 5811 // Let's replace with provided value then. 5812 Replacement = AlternativeReplacement; 5813 } 5814 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5815 } 5816 5817 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5818 /// where the divisor is constant and the comparison target is zero, 5819 /// return a DAG expression that will generate the same comparison result 5820 /// using only multiplications, additions and shifts/rotations. 5821 /// Ref: "Hacker's Delight" 10-17. 5822 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5823 SDValue CompTargetNode, 5824 ISD::CondCode Cond, 5825 DAGCombinerInfo &DCI, 5826 const SDLoc &DL) const { 5827 SmallVector<SDNode *, 5> Built; 5828 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5829 DCI, DL, Built)) { 5830 for (SDNode *N : Built) 5831 DCI.AddToWorklist(N); 5832 return Folded; 5833 } 5834 5835 return SDValue(); 5836 } 5837 5838 SDValue 5839 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5840 SDValue CompTargetNode, ISD::CondCode Cond, 5841 DAGCombinerInfo &DCI, const SDLoc &DL, 5842 SmallVectorImpl<SDNode *> &Created) const { 5843 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5844 // - D must be constant, with D = D0 * 2^K where D0 is odd 5845 // - P is the multiplicative inverse of D0 modulo 2^W 5846 // - Q = floor(((2^W) - 1) / D) 5847 // where W is the width of the common type of N and D. 5848 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5849 "Only applicable for (in)equality comparisons."); 5850 5851 SelectionDAG &DAG = DCI.DAG; 5852 5853 EVT VT = REMNode.getValueType(); 5854 EVT SVT = VT.getScalarType(); 5855 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 5856 EVT ShSVT = ShVT.getScalarType(); 5857 5858 // If MUL is unavailable, we cannot proceed in any case. 5859 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5860 return SDValue(); 5861 5862 bool ComparingWithAllZeros = true; 5863 bool AllComparisonsWithNonZerosAreTautological = true; 5864 bool HadTautologicalLanes = false; 5865 bool AllLanesAreTautological = true; 5866 bool HadEvenDivisor = false; 5867 bool AllDivisorsArePowerOfTwo = true; 5868 bool HadTautologicalInvertedLanes = false; 5869 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 5870 5871 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 5872 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5873 if (CDiv->isZero()) 5874 return false; 5875 5876 const APInt &D = CDiv->getAPIntValue(); 5877 const APInt &Cmp = CCmp->getAPIntValue(); 5878 5879 ComparingWithAllZeros &= Cmp.isZero(); 5880 5881 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5882 // if C2 is not less than C1, the comparison is always false. 5883 // But we will only be able to produce the comparison that will give the 5884 // opposive tautological answer. So this lane would need to be fixed up. 5885 bool TautologicalInvertedLane = D.ule(Cmp); 5886 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 5887 5888 // If all lanes are tautological (either all divisors are ones, or divisor 5889 // is not greater than the constant we are comparing with), 5890 // we will prefer to avoid the fold. 5891 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 5892 HadTautologicalLanes |= TautologicalLane; 5893 AllLanesAreTautological &= TautologicalLane; 5894 5895 // If we are comparing with non-zero, we need'll need to subtract said 5896 // comparison value from the LHS. But there is no point in doing that if 5897 // every lane where we are comparing with non-zero is tautological.. 5898 if (!Cmp.isZero()) 5899 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 5900 5901 // Decompose D into D0 * 2^K 5902 unsigned K = D.countTrailingZeros(); 5903 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 5904 APInt D0 = D.lshr(K); 5905 5906 // D is even if it has trailing zeros. 5907 HadEvenDivisor |= (K != 0); 5908 // D is a power-of-two if D0 is one. 5909 // If all divisors are power-of-two, we will prefer to avoid the fold. 5910 AllDivisorsArePowerOfTwo &= D0.isOne(); 5911 5912 // P = inv(D0, 2^W) 5913 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5914 unsigned W = D.getBitWidth(); 5915 APInt P = D0.zext(W + 1) 5916 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5917 .trunc(W); 5918 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 5919 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 5920 5921 // Q = floor((2^W - 1) u/ D) 5922 // R = ((2^W - 1) u% D) 5923 APInt Q, R; 5924 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 5925 5926 // If we are comparing with zero, then that comparison constant is okay, 5927 // else it may need to be one less than that. 5928 if (Cmp.ugt(R)) 5929 Q -= 1; 5930 5931 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 5932 "We are expecting that K is always less than all-ones for ShSVT"); 5933 5934 // If the lane is tautological the result can be constant-folded. 5935 if (TautologicalLane) { 5936 // Set P and K amount to a bogus values so we can try to splat them. 5937 P = 0; 5938 K = -1; 5939 // And ensure that comparison constant is tautological, 5940 // it will always compare true/false. 5941 Q = -1; 5942 } 5943 5944 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5945 KAmts.push_back( 5946 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5947 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5948 return true; 5949 }; 5950 5951 SDValue N = REMNode.getOperand(0); 5952 SDValue D = REMNode.getOperand(1); 5953 5954 // Collect the values from each element. 5955 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 5956 return SDValue(); 5957 5958 // If all lanes are tautological, the result can be constant-folded. 5959 if (AllLanesAreTautological) 5960 return SDValue(); 5961 5962 // If this is a urem by a powers-of-two, avoid the fold since it can be 5963 // best implemented as a bit test. 5964 if (AllDivisorsArePowerOfTwo) 5965 return SDValue(); 5966 5967 SDValue PVal, KVal, QVal; 5968 if (D.getOpcode() == ISD::BUILD_VECTOR) { 5969 if (HadTautologicalLanes) { 5970 // Try to turn PAmts into a splat, since we don't care about the values 5971 // that are currently '0'. If we can't, just keep '0'`s. 5972 turnVectorIntoSplatVector(PAmts, isNullConstant); 5973 // Try to turn KAmts into a splat, since we don't care about the values 5974 // that are currently '-1'. If we can't, change them to '0'`s. 5975 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5976 DAG.getConstant(0, DL, ShSVT)); 5977 } 5978 5979 PVal = DAG.getBuildVector(VT, DL, PAmts); 5980 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5981 QVal = DAG.getBuildVector(VT, DL, QAmts); 5982 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 5983 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 5984 "Expected matchBinaryPredicate to return one element for " 5985 "SPLAT_VECTORs"); 5986 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 5987 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 5988 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 5989 } else { 5990 PVal = PAmts[0]; 5991 KVal = KAmts[0]; 5992 QVal = QAmts[0]; 5993 } 5994 5995 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 5996 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 5997 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 5998 assert(CompTargetNode.getValueType() == N.getValueType() && 5999 "Expecting that the types on LHS and RHS of comparisons match."); 6000 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6001 } 6002 6003 // (mul N, P) 6004 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6005 Created.push_back(Op0.getNode()); 6006 6007 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6008 // divisors as a performance improvement, since rotating by 0 is a no-op. 6009 if (HadEvenDivisor) { 6010 // We need ROTR to do this. 6011 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6012 return SDValue(); 6013 // UREM: (rotr (mul N, P), K) 6014 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6015 Created.push_back(Op0.getNode()); 6016 } 6017 6018 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6019 SDValue NewCC = 6020 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6021 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6022 if (!HadTautologicalInvertedLanes) 6023 return NewCC; 6024 6025 // If any lanes previously compared always-false, the NewCC will give 6026 // always-true result for them, so we need to fixup those lanes. 6027 // Or the other way around for inequality predicate. 6028 assert(VT.isVector() && "Can/should only get here for vectors."); 6029 Created.push_back(NewCC.getNode()); 6030 6031 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6032 // if C2 is not less than C1, the comparison is always false. 6033 // But we have produced the comparison that will give the 6034 // opposive tautological answer. So these lanes would need to be fixed up. 6035 SDValue TautologicalInvertedChannels = 6036 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6037 Created.push_back(TautologicalInvertedChannels.getNode()); 6038 6039 // NOTE: we avoid letting illegal types through even if we're before legalize 6040 // ops – legalization has a hard time producing good code for this. 6041 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6042 // If we have a vector select, let's replace the comparison results in the 6043 // affected lanes with the correct tautological result. 6044 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6045 DL, SETCCVT, SETCCVT); 6046 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6047 Replacement, NewCC); 6048 } 6049 6050 // Else, we can just invert the comparison result in the appropriate lanes. 6051 // 6052 // NOTE: see the note above VSELECT above. 6053 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6054 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6055 TautologicalInvertedChannels); 6056 6057 return SDValue(); // Don't know how to lower. 6058 } 6059 6060 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6061 /// where the divisor is constant and the comparison target is zero, 6062 /// return a DAG expression that will generate the same comparison result 6063 /// using only multiplications, additions and shifts/rotations. 6064 /// Ref: "Hacker's Delight" 10-17. 6065 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6066 SDValue CompTargetNode, 6067 ISD::CondCode Cond, 6068 DAGCombinerInfo &DCI, 6069 const SDLoc &DL) const { 6070 SmallVector<SDNode *, 7> Built; 6071 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6072 DCI, DL, Built)) { 6073 assert(Built.size() <= 7 && "Max size prediction failed."); 6074 for (SDNode *N : Built) 6075 DCI.AddToWorklist(N); 6076 return Folded; 6077 } 6078 6079 return SDValue(); 6080 } 6081 6082 SDValue 6083 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6084 SDValue CompTargetNode, ISD::CondCode Cond, 6085 DAGCombinerInfo &DCI, const SDLoc &DL, 6086 SmallVectorImpl<SDNode *> &Created) const { 6087 // Fold: 6088 // (seteq/ne (srem N, D), 0) 6089 // To: 6090 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6091 // 6092 // - D must be constant, with D = D0 * 2^K where D0 is odd 6093 // - P is the multiplicative inverse of D0 modulo 2^W 6094 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6095 // - Q = floor((2 * A) / (2^K)) 6096 // where W is the width of the common type of N and D. 6097 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6098 "Only applicable for (in)equality comparisons."); 6099 6100 SelectionDAG &DAG = DCI.DAG; 6101 6102 EVT VT = REMNode.getValueType(); 6103 EVT SVT = VT.getScalarType(); 6104 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6105 EVT ShSVT = ShVT.getScalarType(); 6106 6107 // If we are after ops legalization, and MUL is unavailable, we can not 6108 // proceed. 6109 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6110 return SDValue(); 6111 6112 // TODO: Could support comparing with non-zero too. 6113 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6114 if (!CompTarget || !CompTarget->isZero()) 6115 return SDValue(); 6116 6117 bool HadIntMinDivisor = false; 6118 bool HadOneDivisor = false; 6119 bool AllDivisorsAreOnes = true; 6120 bool HadEvenDivisor = false; 6121 bool NeedToApplyOffset = false; 6122 bool AllDivisorsArePowerOfTwo = true; 6123 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6124 6125 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6126 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6127 if (C->isZero()) 6128 return false; 6129 6130 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6131 6132 // WARNING: this fold is only valid for positive divisors! 6133 APInt D = C->getAPIntValue(); 6134 if (D.isNegative()) 6135 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6136 6137 HadIntMinDivisor |= D.isMinSignedValue(); 6138 6139 // If all divisors are ones, we will prefer to avoid the fold. 6140 HadOneDivisor |= D.isOne(); 6141 AllDivisorsAreOnes &= D.isOne(); 6142 6143 // Decompose D into D0 * 2^K 6144 unsigned K = D.countTrailingZeros(); 6145 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6146 APInt D0 = D.lshr(K); 6147 6148 if (!D.isMinSignedValue()) { 6149 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6150 // we don't care about this lane in this fold, we'll special-handle it. 6151 HadEvenDivisor |= (K != 0); 6152 } 6153 6154 // D is a power-of-two if D0 is one. This includes INT_MIN. 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 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6168 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6169 A.clearLowBits(K); 6170 6171 if (!D.isMinSignedValue()) { 6172 // If divisor INT_MIN, then we don't care about this lane in this fold, 6173 // we'll special-handle it. 6174 NeedToApplyOffset |= A != 0; 6175 } 6176 6177 // Q = floor((2 * A) / (2^K)) 6178 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6179 6180 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6181 "We are expecting that A is always less than all-ones for SVT"); 6182 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6183 "We are expecting that K is always less than all-ones for ShSVT"); 6184 6185 // If the divisor is 1 the result can be constant-folded. Likewise, we 6186 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6187 if (D.isOne()) { 6188 // Set P, A and K to a bogus values so we can try to splat them. 6189 P = 0; 6190 A = -1; 6191 K = -1; 6192 6193 // x ?% 1 == 0 <--> true <--> x u<= -1 6194 Q = -1; 6195 } 6196 6197 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6198 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6199 KAmts.push_back( 6200 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6201 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6202 return true; 6203 }; 6204 6205 SDValue N = REMNode.getOperand(0); 6206 SDValue D = REMNode.getOperand(1); 6207 6208 // Collect the values from each element. 6209 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6210 return SDValue(); 6211 6212 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6213 if (AllDivisorsAreOnes) 6214 return SDValue(); 6215 6216 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6217 // since it can be best implemented as a bit test. 6218 if (AllDivisorsArePowerOfTwo) 6219 return SDValue(); 6220 6221 SDValue PVal, AVal, KVal, QVal; 6222 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6223 if (HadOneDivisor) { 6224 // Try to turn PAmts into a splat, since we don't care about the values 6225 // that are currently '0'. If we can't, just keep '0'`s. 6226 turnVectorIntoSplatVector(PAmts, isNullConstant); 6227 // Try to turn AAmts into a splat, since we don't care about the 6228 // values that are currently '-1'. If we can't, change them to '0'`s. 6229 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6230 DAG.getConstant(0, DL, SVT)); 6231 // Try to turn KAmts into a splat, since we don't care about the values 6232 // that are currently '-1'. If we can't, change them to '0'`s. 6233 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6234 DAG.getConstant(0, DL, ShSVT)); 6235 } 6236 6237 PVal = DAG.getBuildVector(VT, DL, PAmts); 6238 AVal = DAG.getBuildVector(VT, DL, AAmts); 6239 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6240 QVal = DAG.getBuildVector(VT, DL, QAmts); 6241 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6242 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6243 QAmts.size() == 1 && 6244 "Expected matchUnaryPredicate to return one element for scalable " 6245 "vectors"); 6246 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6247 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6248 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6249 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6250 } else { 6251 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6252 PVal = PAmts[0]; 6253 AVal = AAmts[0]; 6254 KVal = KAmts[0]; 6255 QVal = QAmts[0]; 6256 } 6257 6258 // (mul N, P) 6259 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6260 Created.push_back(Op0.getNode()); 6261 6262 if (NeedToApplyOffset) { 6263 // We need ADD to do this. 6264 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6265 return SDValue(); 6266 6267 // (add (mul N, P), A) 6268 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6269 Created.push_back(Op0.getNode()); 6270 } 6271 6272 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6273 // divisors as a performance improvement, since rotating by 0 is a no-op. 6274 if (HadEvenDivisor) { 6275 // We need ROTR to do this. 6276 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6277 return SDValue(); 6278 // SREM: (rotr (add (mul N, P), A), K) 6279 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6280 Created.push_back(Op0.getNode()); 6281 } 6282 6283 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6284 SDValue Fold = 6285 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6286 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6287 6288 // If we didn't have lanes with INT_MIN divisor, then we're done. 6289 if (!HadIntMinDivisor) 6290 return Fold; 6291 6292 // That fold is only valid for positive divisors. Which effectively means, 6293 // it is invalid for INT_MIN divisors. So if we have such a lane, 6294 // we must fix-up results for said lanes. 6295 assert(VT.isVector() && "Can/should only get here for vectors."); 6296 6297 // NOTE: we avoid letting illegal types through even if we're before legalize 6298 // ops – legalization has a hard time producing good code for the code that 6299 // follows. 6300 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6301 !isOperationLegalOrCustom(ISD::AND, VT) || 6302 !isOperationLegalOrCustom(Cond, VT) || 6303 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6304 return SDValue(); 6305 6306 Created.push_back(Fold.getNode()); 6307 6308 SDValue IntMin = DAG.getConstant( 6309 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6310 SDValue IntMax = DAG.getConstant( 6311 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6312 SDValue Zero = 6313 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6314 6315 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6316 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6317 Created.push_back(DivisorIsIntMin.getNode()); 6318 6319 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6320 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6321 Created.push_back(Masked.getNode()); 6322 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6323 Created.push_back(MaskedIsZero.getNode()); 6324 6325 // To produce final result we need to blend 2 vectors: 'SetCC' and 6326 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6327 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6328 // constant-folded, select can get lowered to a shuffle with constant mask. 6329 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6330 MaskedIsZero, Fold); 6331 6332 return Blended; 6333 } 6334 6335 bool TargetLowering:: 6336 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6337 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6338 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6339 "be a constant integer"); 6340 return true; 6341 } 6342 6343 return false; 6344 } 6345 6346 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6347 const DenormalMode &Mode) const { 6348 SDLoc DL(Op); 6349 EVT VT = Op.getValueType(); 6350 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6351 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6352 // Testing it with denormal inputs to avoid wrong estimate. 6353 if (Mode.Input == DenormalMode::IEEE) { 6354 // This is specifically a check for the handling of denormal inputs, 6355 // not the result. 6356 6357 // Test = fabs(X) < SmallestNormal 6358 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6359 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6360 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6361 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6362 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6363 } 6364 // Test = X == 0.0 6365 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6366 } 6367 6368 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6369 bool LegalOps, bool OptForSize, 6370 NegatibleCost &Cost, 6371 unsigned Depth) const { 6372 // fneg is removable even if it has multiple uses. 6373 if (Op.getOpcode() == ISD::FNEG) { 6374 Cost = NegatibleCost::Cheaper; 6375 return Op.getOperand(0); 6376 } 6377 6378 // Don't recurse exponentially. 6379 if (Depth > SelectionDAG::MaxRecursionDepth) 6380 return SDValue(); 6381 6382 // Pre-increment recursion depth for use in recursive calls. 6383 ++Depth; 6384 const SDNodeFlags Flags = Op->getFlags(); 6385 const TargetOptions &Options = DAG.getTarget().Options; 6386 EVT VT = Op.getValueType(); 6387 unsigned Opcode = Op.getOpcode(); 6388 6389 // Don't allow anything with multiple uses unless we know it is free. 6390 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6391 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6392 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6393 if (!IsFreeExtend) 6394 return SDValue(); 6395 } 6396 6397 auto RemoveDeadNode = [&](SDValue N) { 6398 if (N && N.getNode()->use_empty()) 6399 DAG.RemoveDeadNode(N.getNode()); 6400 }; 6401 6402 SDLoc DL(Op); 6403 6404 // Because getNegatedExpression can delete nodes we need a handle to keep 6405 // temporary nodes alive in case the recursion manages to create an identical 6406 // node. 6407 std::list<HandleSDNode> Handles; 6408 6409 switch (Opcode) { 6410 case ISD::ConstantFP: { 6411 // Don't invert constant FP values after legalization unless the target says 6412 // the negated constant is legal. 6413 bool IsOpLegal = 6414 isOperationLegal(ISD::ConstantFP, VT) || 6415 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6416 OptForSize); 6417 6418 if (LegalOps && !IsOpLegal) 6419 break; 6420 6421 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6422 V.changeSign(); 6423 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6424 6425 // If we already have the use of the negated floating constant, it is free 6426 // to negate it even it has multiple uses. 6427 if (!Op.hasOneUse() && CFP.use_empty()) 6428 break; 6429 Cost = NegatibleCost::Neutral; 6430 return CFP; 6431 } 6432 case ISD::BUILD_VECTOR: { 6433 // Only permit BUILD_VECTOR of constants. 6434 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6435 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6436 })) 6437 break; 6438 6439 bool IsOpLegal = 6440 (isOperationLegal(ISD::ConstantFP, VT) && 6441 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6442 llvm::all_of(Op->op_values(), [&](SDValue N) { 6443 return N.isUndef() || 6444 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6445 OptForSize); 6446 }); 6447 6448 if (LegalOps && !IsOpLegal) 6449 break; 6450 6451 SmallVector<SDValue, 4> Ops; 6452 for (SDValue C : Op->op_values()) { 6453 if (C.isUndef()) { 6454 Ops.push_back(C); 6455 continue; 6456 } 6457 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6458 V.changeSign(); 6459 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6460 } 6461 Cost = NegatibleCost::Neutral; 6462 return DAG.getBuildVector(VT, DL, Ops); 6463 } 6464 case ISD::FADD: { 6465 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6466 break; 6467 6468 // After operation legalization, it might not be legal to create new FSUBs. 6469 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6470 break; 6471 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6472 6473 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6474 NegatibleCost CostX = NegatibleCost::Expensive; 6475 SDValue NegX = 6476 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6477 // Prevent this node from being deleted by the next call. 6478 if (NegX) 6479 Handles.emplace_back(NegX); 6480 6481 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6482 NegatibleCost CostY = NegatibleCost::Expensive; 6483 SDValue NegY = 6484 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6485 6486 // We're done with the handles. 6487 Handles.clear(); 6488 6489 // Negate the X if its cost is less or equal than Y. 6490 if (NegX && (CostX <= CostY)) { 6491 Cost = CostX; 6492 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6493 if (NegY != N) 6494 RemoveDeadNode(NegY); 6495 return N; 6496 } 6497 6498 // Negate the Y if it is not expensive. 6499 if (NegY) { 6500 Cost = CostY; 6501 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6502 if (NegX != N) 6503 RemoveDeadNode(NegX); 6504 return N; 6505 } 6506 break; 6507 } 6508 case ISD::FSUB: { 6509 // We can't turn -(A-B) into B-A when we honor signed zeros. 6510 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6511 break; 6512 6513 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6514 // fold (fneg (fsub 0, Y)) -> Y 6515 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6516 if (C->isZero()) { 6517 Cost = NegatibleCost::Cheaper; 6518 return Y; 6519 } 6520 6521 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6522 Cost = NegatibleCost::Neutral; 6523 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6524 } 6525 case ISD::FMUL: 6526 case ISD::FDIV: { 6527 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6528 6529 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6530 NegatibleCost CostX = NegatibleCost::Expensive; 6531 SDValue NegX = 6532 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6533 // Prevent this node from being deleted by the next call. 6534 if (NegX) 6535 Handles.emplace_back(NegX); 6536 6537 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6538 NegatibleCost CostY = NegatibleCost::Expensive; 6539 SDValue NegY = 6540 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6541 6542 // We're done with the handles. 6543 Handles.clear(); 6544 6545 // Negate the X if its cost is less or equal than Y. 6546 if (NegX && (CostX <= CostY)) { 6547 Cost = CostX; 6548 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6549 if (NegY != N) 6550 RemoveDeadNode(NegY); 6551 return N; 6552 } 6553 6554 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6555 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6556 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6557 break; 6558 6559 // Negate the Y if it is not expensive. 6560 if (NegY) { 6561 Cost = CostY; 6562 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6563 if (NegX != N) 6564 RemoveDeadNode(NegX); 6565 return N; 6566 } 6567 break; 6568 } 6569 case ISD::FMA: 6570 case ISD::FMAD: { 6571 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6572 break; 6573 6574 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6575 NegatibleCost CostZ = NegatibleCost::Expensive; 6576 SDValue NegZ = 6577 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6578 // Give up if fail to negate the Z. 6579 if (!NegZ) 6580 break; 6581 6582 // Prevent this node from being deleted by the next two calls. 6583 Handles.emplace_back(NegZ); 6584 6585 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6586 NegatibleCost CostX = NegatibleCost::Expensive; 6587 SDValue NegX = 6588 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6589 // Prevent this node from being deleted by the next call. 6590 if (NegX) 6591 Handles.emplace_back(NegX); 6592 6593 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6594 NegatibleCost CostY = NegatibleCost::Expensive; 6595 SDValue NegY = 6596 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6597 6598 // We're done with the handles. 6599 Handles.clear(); 6600 6601 // Negate the X if its cost is less or equal than Y. 6602 if (NegX && (CostX <= CostY)) { 6603 Cost = std::min(CostX, CostZ); 6604 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6605 if (NegY != N) 6606 RemoveDeadNode(NegY); 6607 return N; 6608 } 6609 6610 // Negate the Y if it is not expensive. 6611 if (NegY) { 6612 Cost = std::min(CostY, CostZ); 6613 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6614 if (NegX != N) 6615 RemoveDeadNode(NegX); 6616 return N; 6617 } 6618 break; 6619 } 6620 6621 case ISD::FP_EXTEND: 6622 case ISD::FSIN: 6623 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6624 OptForSize, Cost, Depth)) 6625 return DAG.getNode(Opcode, DL, VT, NegV); 6626 break; 6627 case ISD::FP_ROUND: 6628 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6629 OptForSize, Cost, Depth)) 6630 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6631 break; 6632 } 6633 6634 return SDValue(); 6635 } 6636 6637 //===----------------------------------------------------------------------===// 6638 // Legalization Utilities 6639 //===----------------------------------------------------------------------===// 6640 6641 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6642 SDValue LHS, SDValue RHS, 6643 SmallVectorImpl<SDValue> &Result, 6644 EVT HiLoVT, SelectionDAG &DAG, 6645 MulExpansionKind Kind, SDValue LL, 6646 SDValue LH, SDValue RL, SDValue RH) const { 6647 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6648 Opcode == ISD::SMUL_LOHI); 6649 6650 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6651 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6652 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6653 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6654 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6655 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6656 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6657 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6658 6659 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6660 return false; 6661 6662 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6663 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6664 6665 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6666 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6667 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6668 6669 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6670 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6671 bool Signed) -> bool { 6672 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6673 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6674 Hi = SDValue(Lo.getNode(), 1); 6675 return true; 6676 } 6677 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6678 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6679 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6680 return true; 6681 } 6682 return false; 6683 }; 6684 6685 SDValue Lo, Hi; 6686 6687 if (!LL.getNode() && !RL.getNode() && 6688 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6689 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6690 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6691 } 6692 6693 if (!LL.getNode()) 6694 return false; 6695 6696 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6697 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6698 DAG.MaskedValueIsZero(RHS, HighMask)) { 6699 // The inputs are both zero-extended. 6700 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6701 Result.push_back(Lo); 6702 Result.push_back(Hi); 6703 if (Opcode != ISD::MUL) { 6704 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6705 Result.push_back(Zero); 6706 Result.push_back(Zero); 6707 } 6708 return true; 6709 } 6710 } 6711 6712 if (!VT.isVector() && Opcode == ISD::MUL && 6713 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6714 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6715 // The input values are both sign-extended. 6716 // TODO non-MUL case? 6717 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6718 Result.push_back(Lo); 6719 Result.push_back(Hi); 6720 return true; 6721 } 6722 } 6723 6724 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6725 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6726 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6727 6728 if (!LH.getNode() && !RH.getNode() && 6729 isOperationLegalOrCustom(ISD::SRL, VT) && 6730 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6731 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6732 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6733 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6734 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6735 } 6736 6737 if (!LH.getNode()) 6738 return false; 6739 6740 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6741 return false; 6742 6743 Result.push_back(Lo); 6744 6745 if (Opcode == ISD::MUL) { 6746 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6747 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6748 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6749 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6750 Result.push_back(Hi); 6751 return true; 6752 } 6753 6754 // Compute the full width result. 6755 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6756 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6757 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6758 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6759 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6760 }; 6761 6762 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6763 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6764 return false; 6765 6766 // This is effectively the add part of a multiply-add of half-sized operands, 6767 // so it cannot overflow. 6768 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6769 6770 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6771 return false; 6772 6773 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6774 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6775 6776 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6777 isOperationLegalOrCustom(ISD::ADDE, VT)); 6778 if (UseGlue) 6779 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6780 Merge(Lo, Hi)); 6781 else 6782 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6783 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6784 6785 SDValue Carry = Next.getValue(1); 6786 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6787 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6788 6789 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6790 return false; 6791 6792 if (UseGlue) 6793 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6794 Carry); 6795 else 6796 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6797 Zero, Carry); 6798 6799 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6800 6801 if (Opcode == ISD::SMUL_LOHI) { 6802 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6803 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6804 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6805 6806 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6807 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6808 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6809 } 6810 6811 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6812 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6813 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6814 return true; 6815 } 6816 6817 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6818 SelectionDAG &DAG, MulExpansionKind Kind, 6819 SDValue LL, SDValue LH, SDValue RL, 6820 SDValue RH) const { 6821 SmallVector<SDValue, 2> Result; 6822 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6823 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6824 DAG, Kind, LL, LH, RL, RH); 6825 if (Ok) { 6826 assert(Result.size() == 2); 6827 Lo = Result[0]; 6828 Hi = Result[1]; 6829 } 6830 return Ok; 6831 } 6832 6833 // Check that (every element of) Z is undef or not an exact multiple of BW. 6834 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6835 return ISD::matchUnaryPredicate( 6836 Z, 6837 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6838 true); 6839 } 6840 6841 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 6842 SelectionDAG &DAG) const { 6843 EVT VT = Node->getValueType(0); 6844 6845 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6846 !isOperationLegalOrCustom(ISD::SRL, VT) || 6847 !isOperationLegalOrCustom(ISD::SUB, VT) || 6848 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6849 return SDValue(); 6850 6851 SDValue X = Node->getOperand(0); 6852 SDValue Y = Node->getOperand(1); 6853 SDValue Z = Node->getOperand(2); 6854 6855 unsigned BW = VT.getScalarSizeInBits(); 6856 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6857 SDLoc DL(SDValue(Node, 0)); 6858 6859 EVT ShVT = Z.getValueType(); 6860 6861 // If a funnel shift in the other direction is more supported, use it. 6862 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6863 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6864 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6865 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6866 // fshl X, Y, Z -> fshr X, Y, -Z 6867 // fshr X, Y, Z -> fshl X, Y, -Z 6868 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6869 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 6870 } else { 6871 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 6872 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 6873 SDValue One = DAG.getConstant(1, DL, ShVT); 6874 if (IsFSHL) { 6875 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6876 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 6877 } else { 6878 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6879 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 6880 } 6881 Z = DAG.getNOT(DL, Z, ShVT); 6882 } 6883 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 6884 } 6885 6886 SDValue ShX, ShY; 6887 SDValue ShAmt, InvShAmt; 6888 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6889 // fshl: X << C | Y >> (BW - C) 6890 // fshr: X << (BW - C) | Y >> C 6891 // where C = Z % BW is not zero 6892 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6893 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6894 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 6895 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 6896 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6897 } else { 6898 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 6899 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 6900 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 6901 if (isPowerOf2_32(BW)) { 6902 // Z % BW -> Z & (BW - 1) 6903 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 6904 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 6905 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 6906 } else { 6907 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6908 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6909 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 6910 } 6911 6912 SDValue One = DAG.getConstant(1, DL, ShVT); 6913 if (IsFSHL) { 6914 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 6915 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 6916 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 6917 } else { 6918 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 6919 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 6920 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 6921 } 6922 } 6923 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 6924 } 6925 6926 // TODO: Merge with expandFunnelShift. 6927 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 6928 SelectionDAG &DAG) const { 6929 EVT VT = Node->getValueType(0); 6930 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6931 bool IsLeft = Node->getOpcode() == ISD::ROTL; 6932 SDValue Op0 = Node->getOperand(0); 6933 SDValue Op1 = Node->getOperand(1); 6934 SDLoc DL(SDValue(Node, 0)); 6935 6936 EVT ShVT = Op1.getValueType(); 6937 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6938 6939 // If a rotate in the other direction is more supported, use it. 6940 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 6941 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6942 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 6943 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6944 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 6945 } 6946 6947 if (!AllowVectorOps && VT.isVector() && 6948 (!isOperationLegalOrCustom(ISD::SHL, VT) || 6949 !isOperationLegalOrCustom(ISD::SRL, VT) || 6950 !isOperationLegalOrCustom(ISD::SUB, VT) || 6951 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 6952 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6953 return SDValue(); 6954 6955 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 6956 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 6957 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 6958 SDValue ShVal; 6959 SDValue HsVal; 6960 if (isPowerOf2_32(EltSizeInBits)) { 6961 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 6962 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 6963 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6964 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 6965 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6966 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 6967 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 6968 } else { 6969 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 6970 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 6971 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 6972 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 6973 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6974 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 6975 SDValue One = DAG.getConstant(1, DL, ShVT); 6976 HsVal = 6977 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 6978 } 6979 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 6980 } 6981 6982 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 6983 SelectionDAG &DAG) const { 6984 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 6985 EVT VT = Node->getValueType(0); 6986 unsigned VTBits = VT.getScalarSizeInBits(); 6987 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 6988 6989 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 6990 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 6991 SDValue ShOpLo = Node->getOperand(0); 6992 SDValue ShOpHi = Node->getOperand(1); 6993 SDValue ShAmt = Node->getOperand(2); 6994 EVT ShAmtVT = ShAmt.getValueType(); 6995 EVT ShAmtCCVT = 6996 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 6997 SDLoc dl(Node); 6998 6999 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7000 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7001 // away during isel. 7002 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7003 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7004 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7005 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7006 : DAG.getConstant(0, dl, VT); 7007 7008 SDValue Tmp2, Tmp3; 7009 if (IsSHL) { 7010 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7011 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7012 } else { 7013 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7014 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7015 } 7016 7017 // If the shift amount is larger or equal than the width of a part we don't 7018 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7019 // values for large shift amounts. 7020 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7021 DAG.getConstant(VTBits, dl, ShAmtVT)); 7022 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7023 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7024 7025 if (IsSHL) { 7026 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7027 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7028 } else { 7029 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7030 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7031 } 7032 } 7033 7034 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7035 SelectionDAG &DAG) const { 7036 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7037 SDValue Src = Node->getOperand(OpNo); 7038 EVT SrcVT = Src.getValueType(); 7039 EVT DstVT = Node->getValueType(0); 7040 SDLoc dl(SDValue(Node, 0)); 7041 7042 // FIXME: Only f32 to i64 conversions are supported. 7043 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7044 return false; 7045 7046 if (Node->isStrictFPOpcode()) 7047 // When a NaN is converted to an integer a trap is allowed. We can't 7048 // use this expansion here because it would eliminate that trap. Other 7049 // traps are also allowed and cannot be eliminated. See 7050 // IEEE 754-2008 sec 5.8. 7051 return false; 7052 7053 // Expand f32 -> i64 conversion 7054 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7055 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7056 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7057 EVT IntVT = SrcVT.changeTypeToInteger(); 7058 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7059 7060 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7061 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7062 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7063 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7064 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7065 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7066 7067 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7068 7069 SDValue ExponentBits = DAG.getNode( 7070 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7071 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7072 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7073 7074 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7075 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7076 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7077 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7078 7079 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7080 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7081 DAG.getConstant(0x00800000, dl, IntVT)); 7082 7083 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7084 7085 R = DAG.getSelectCC( 7086 dl, Exponent, ExponentLoBit, 7087 DAG.getNode(ISD::SHL, dl, DstVT, R, 7088 DAG.getZExtOrTrunc( 7089 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7090 dl, IntShVT)), 7091 DAG.getNode(ISD::SRL, dl, DstVT, R, 7092 DAG.getZExtOrTrunc( 7093 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7094 dl, IntShVT)), 7095 ISD::SETGT); 7096 7097 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7098 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7099 7100 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7101 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7102 return true; 7103 } 7104 7105 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7106 SDValue &Chain, 7107 SelectionDAG &DAG) const { 7108 SDLoc dl(SDValue(Node, 0)); 7109 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7110 SDValue Src = Node->getOperand(OpNo); 7111 7112 EVT SrcVT = Src.getValueType(); 7113 EVT DstVT = Node->getValueType(0); 7114 EVT SetCCVT = 7115 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7116 EVT DstSetCCVT = 7117 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7118 7119 // Only expand vector types if we have the appropriate vector bit operations. 7120 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7121 ISD::FP_TO_SINT; 7122 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7123 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7124 return false; 7125 7126 // If the maximum float value is smaller then the signed integer range, 7127 // the destination signmask can't be represented by the float, so we can 7128 // just use FP_TO_SINT directly. 7129 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7130 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7131 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7132 if (APFloat::opOverflow & 7133 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7134 if (Node->isStrictFPOpcode()) { 7135 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7136 { Node->getOperand(0), Src }); 7137 Chain = Result.getValue(1); 7138 } else 7139 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7140 return true; 7141 } 7142 7143 // Don't expand it if there isn't cheap fsub instruction. 7144 if (!isOperationLegalOrCustom( 7145 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7146 return false; 7147 7148 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7149 SDValue Sel; 7150 7151 if (Node->isStrictFPOpcode()) { 7152 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7153 Node->getOperand(0), /*IsSignaling*/ true); 7154 Chain = Sel.getValue(1); 7155 } else { 7156 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7157 } 7158 7159 bool Strict = Node->isStrictFPOpcode() || 7160 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7161 7162 if (Strict) { 7163 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7164 // signmask then offset (the result of which should be fully representable). 7165 // Sel = Src < 0x8000000000000000 7166 // FltOfs = select Sel, 0, 0x8000000000000000 7167 // IntOfs = select Sel, 0, 0x8000000000000000 7168 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7169 7170 // TODO: Should any fast-math-flags be set for the FSUB? 7171 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7172 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7173 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7174 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7175 DAG.getConstant(0, dl, DstVT), 7176 DAG.getConstant(SignMask, dl, DstVT)); 7177 SDValue SInt; 7178 if (Node->isStrictFPOpcode()) { 7179 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7180 { Chain, Src, FltOfs }); 7181 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7182 { Val.getValue(1), Val }); 7183 Chain = SInt.getValue(1); 7184 } else { 7185 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7186 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7187 } 7188 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7189 } else { 7190 // Expand based on maximum range of FP_TO_SINT: 7191 // True = fp_to_sint(Src) 7192 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7193 // Result = select (Src < 0x8000000000000000), True, False 7194 7195 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7196 // TODO: Should any fast-math-flags be set for the FSUB? 7197 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7198 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7199 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7200 DAG.getConstant(SignMask, dl, DstVT)); 7201 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7202 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7203 } 7204 return true; 7205 } 7206 7207 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7208 SDValue &Chain, 7209 SelectionDAG &DAG) const { 7210 // This transform is not correct for converting 0 when rounding mode is set 7211 // to round toward negative infinity which will produce -0.0. So disable under 7212 // strictfp. 7213 if (Node->isStrictFPOpcode()) 7214 return false; 7215 7216 SDValue Src = Node->getOperand(0); 7217 EVT SrcVT = Src.getValueType(); 7218 EVT DstVT = Node->getValueType(0); 7219 7220 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7221 return false; 7222 7223 // Only expand vector types if we have the appropriate vector bit operations. 7224 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7225 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7226 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7227 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7228 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7229 return false; 7230 7231 SDLoc dl(SDValue(Node, 0)); 7232 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7233 7234 // Implementation of unsigned i64 to f64 following the algorithm in 7235 // __floatundidf in compiler_rt. This implementation performs rounding 7236 // correctly in all rounding modes with the exception of converting 0 7237 // when rounding toward negative infinity. In that case the fsub will produce 7238 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7239 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7240 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7241 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7242 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7243 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7244 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7245 7246 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7247 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7248 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7249 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7250 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7251 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7252 SDValue HiSub = 7253 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7254 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7255 return true; 7256 } 7257 7258 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7259 SelectionDAG &DAG) const { 7260 SDLoc dl(Node); 7261 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7262 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7263 EVT VT = Node->getValueType(0); 7264 7265 if (VT.isScalableVector()) 7266 report_fatal_error( 7267 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7268 7269 if (isOperationLegalOrCustom(NewOp, VT)) { 7270 SDValue Quiet0 = Node->getOperand(0); 7271 SDValue Quiet1 = Node->getOperand(1); 7272 7273 if (!Node->getFlags().hasNoNaNs()) { 7274 // Insert canonicalizes if it's possible we need to quiet to get correct 7275 // sNaN behavior. 7276 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7277 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7278 Node->getFlags()); 7279 } 7280 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7281 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7282 Node->getFlags()); 7283 } 7284 } 7285 7286 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7287 } 7288 7289 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7290 // instead if there are no NaNs. 7291 if (Node->getFlags().hasNoNaNs()) { 7292 unsigned IEEE2018Op = 7293 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7294 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7295 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7296 Node->getOperand(1), Node->getFlags()); 7297 } 7298 } 7299 7300 // If none of the above worked, but there are no NaNs, then expand to 7301 // a compare/select sequence. This is required for correctness since 7302 // InstCombine might have canonicalized a fcmp+select sequence to a 7303 // FMINNUM/FMAXNUM node. If we were to fall through to the default 7304 // expansion to libcall, we might introduce a link-time dependency 7305 // on libm into a file that originally did not have one. 7306 if (Node->getFlags().hasNoNaNs()) { 7307 ISD::CondCode Pred = 7308 Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7309 SDValue Op1 = Node->getOperand(0); 7310 SDValue Op2 = Node->getOperand(1); 7311 SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred); 7312 // Copy FMF flags, but always set the no-signed-zeros flag 7313 // as this is implied by the FMINNUM/FMAXNUM semantics. 7314 SDNodeFlags Flags = Node->getFlags(); 7315 Flags.setNoSignedZeros(true); 7316 SelCC->setFlags(Flags); 7317 return SelCC; 7318 } 7319 7320 return SDValue(); 7321 } 7322 7323 // Only expand vector types if we have the appropriate vector bit operations. 7324 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7325 assert(VT.isVector() && "Expected vector type"); 7326 unsigned Len = VT.getScalarSizeInBits(); 7327 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7328 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7329 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7330 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7331 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7332 } 7333 7334 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7335 SDLoc dl(Node); 7336 EVT VT = Node->getValueType(0); 7337 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7338 SDValue Op = Node->getOperand(0); 7339 unsigned Len = VT.getScalarSizeInBits(); 7340 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7341 7342 // TODO: Add support for irregular type lengths. 7343 if (!(Len <= 128 && Len % 8 == 0)) 7344 return SDValue(); 7345 7346 // Only expand vector types if we have the appropriate vector bit operations. 7347 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7348 return SDValue(); 7349 7350 // This is the "best" algorithm from 7351 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7352 SDValue Mask55 = 7353 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7354 SDValue Mask33 = 7355 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7356 SDValue Mask0F = 7357 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7358 SDValue Mask01 = 7359 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7360 7361 // v = v - ((v >> 1) & 0x55555555...) 7362 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7363 DAG.getNode(ISD::AND, dl, VT, 7364 DAG.getNode(ISD::SRL, dl, VT, Op, 7365 DAG.getConstant(1, dl, ShVT)), 7366 Mask55)); 7367 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7368 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7369 DAG.getNode(ISD::AND, dl, VT, 7370 DAG.getNode(ISD::SRL, dl, VT, Op, 7371 DAG.getConstant(2, dl, ShVT)), 7372 Mask33)); 7373 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7374 Op = DAG.getNode(ISD::AND, dl, VT, 7375 DAG.getNode(ISD::ADD, dl, VT, Op, 7376 DAG.getNode(ISD::SRL, dl, VT, Op, 7377 DAG.getConstant(4, dl, ShVT))), 7378 Mask0F); 7379 // v = (v * 0x01010101...) >> (Len - 8) 7380 if (Len > 8) 7381 Op = 7382 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7383 DAG.getConstant(Len - 8, dl, ShVT)); 7384 7385 return Op; 7386 } 7387 7388 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7389 SDLoc dl(Node); 7390 EVT VT = Node->getValueType(0); 7391 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7392 SDValue Op = Node->getOperand(0); 7393 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7394 7395 // If the non-ZERO_UNDEF version is supported we can use that instead. 7396 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7397 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7398 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7399 7400 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7401 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7402 EVT SetCCVT = 7403 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7404 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7405 SDValue Zero = DAG.getConstant(0, dl, VT); 7406 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7407 return DAG.getSelect(dl, VT, SrcIsZero, 7408 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7409 } 7410 7411 // Only expand vector types if we have the appropriate vector bit operations. 7412 // This includes the operations needed to expand CTPOP if it isn't supported. 7413 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7414 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7415 !canExpandVectorCTPOP(*this, VT)) || 7416 !isOperationLegalOrCustom(ISD::SRL, VT) || 7417 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7418 return SDValue(); 7419 7420 // for now, we do this: 7421 // x = x | (x >> 1); 7422 // x = x | (x >> 2); 7423 // ... 7424 // x = x | (x >>16); 7425 // x = x | (x >>32); // for 64-bit input 7426 // return popcount(~x); 7427 // 7428 // Ref: "Hacker's Delight" by Henry Warren 7429 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 7430 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7431 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7432 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7433 } 7434 Op = DAG.getNOT(dl, Op, VT); 7435 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7436 } 7437 7438 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7439 SDLoc dl(Node); 7440 EVT VT = Node->getValueType(0); 7441 SDValue Op = Node->getOperand(0); 7442 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7443 7444 // If the non-ZERO_UNDEF version is supported we can use that instead. 7445 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7446 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7447 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7448 7449 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7450 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7451 EVT SetCCVT = 7452 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7453 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7454 SDValue Zero = DAG.getConstant(0, dl, VT); 7455 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7456 return DAG.getSelect(dl, VT, SrcIsZero, 7457 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7458 } 7459 7460 // Only expand vector types if we have the appropriate vector bit operations. 7461 // This includes the operations needed to expand CTPOP if it isn't supported. 7462 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7463 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7464 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7465 !canExpandVectorCTPOP(*this, VT)) || 7466 !isOperationLegalOrCustom(ISD::SUB, VT) || 7467 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7468 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7469 return SDValue(); 7470 7471 // for now, we use: { return popcount(~x & (x - 1)); } 7472 // unless the target has ctlz but not ctpop, in which case we use: 7473 // { return 32 - nlz(~x & (x-1)); } 7474 // Ref: "Hacker's Delight" by Henry Warren 7475 SDValue Tmp = DAG.getNode( 7476 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7477 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7478 7479 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7480 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7481 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7482 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7483 } 7484 7485 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7486 } 7487 7488 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7489 bool IsNegative) const { 7490 SDLoc dl(N); 7491 EVT VT = N->getValueType(0); 7492 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7493 SDValue Op = N->getOperand(0); 7494 7495 // abs(x) -> smax(x,sub(0,x)) 7496 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7497 isOperationLegal(ISD::SMAX, VT)) { 7498 SDValue Zero = DAG.getConstant(0, dl, VT); 7499 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7500 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7501 } 7502 7503 // abs(x) -> umin(x,sub(0,x)) 7504 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7505 isOperationLegal(ISD::UMIN, VT)) { 7506 SDValue Zero = DAG.getConstant(0, dl, VT); 7507 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7508 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7509 } 7510 7511 // 0 - abs(x) -> smin(x, sub(0,x)) 7512 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7513 isOperationLegal(ISD::SMIN, VT)) { 7514 SDValue Zero = DAG.getConstant(0, dl, VT); 7515 return DAG.getNode(ISD::SMIN, dl, VT, Op, 7516 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7517 } 7518 7519 // Only expand vector types if we have the appropriate vector operations. 7520 if (VT.isVector() && 7521 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7522 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7523 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7524 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7525 return SDValue(); 7526 7527 SDValue Shift = 7528 DAG.getNode(ISD::SRA, dl, VT, Op, 7529 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7530 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7531 7532 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 7533 if (!IsNegative) 7534 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 7535 7536 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7537 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7538 } 7539 7540 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7541 SDLoc dl(N); 7542 EVT VT = N->getValueType(0); 7543 SDValue Op = N->getOperand(0); 7544 7545 if (!VT.isSimple()) 7546 return SDValue(); 7547 7548 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7549 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7550 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7551 default: 7552 return SDValue(); 7553 case MVT::i16: 7554 // Use a rotate by 8. This can be further expanded if necessary. 7555 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7556 case MVT::i32: 7557 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7558 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7559 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7560 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7561 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7562 DAG.getConstant(0xFF0000, dl, VT)); 7563 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7564 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7565 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7566 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7567 case MVT::i64: 7568 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7569 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7570 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7571 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7572 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7573 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7574 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7575 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7576 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7577 DAG.getConstant(255ULL<<48, dl, VT)); 7578 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7579 DAG.getConstant(255ULL<<40, dl, VT)); 7580 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7581 DAG.getConstant(255ULL<<32, dl, VT)); 7582 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7583 DAG.getConstant(255ULL<<24, dl, VT)); 7584 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7585 DAG.getConstant(255ULL<<16, dl, VT)); 7586 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7587 DAG.getConstant(255ULL<<8 , dl, VT)); 7588 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7589 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7590 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7591 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7592 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7593 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7594 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7595 } 7596 } 7597 7598 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 7599 SDLoc dl(N); 7600 EVT VT = N->getValueType(0); 7601 SDValue Op = N->getOperand(0); 7602 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7603 unsigned Sz = VT.getScalarSizeInBits(); 7604 7605 SDValue Tmp, Tmp2, Tmp3; 7606 7607 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 7608 // and finally the i1 pairs. 7609 // TODO: We can easily support i4/i2 legal types if any target ever does. 7610 if (Sz >= 8 && isPowerOf2_32(Sz)) { 7611 // Create the masks - repeating the pattern every byte. 7612 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 7613 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 7614 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 7615 7616 // BSWAP if the type is wider than a single byte. 7617 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 7618 7619 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 7620 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 7621 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 7622 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 7623 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 7624 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7625 7626 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 7627 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 7628 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 7629 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 7630 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 7631 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7632 7633 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 7634 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 7635 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 7636 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 7637 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 7638 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7639 return Tmp; 7640 } 7641 7642 Tmp = DAG.getConstant(0, dl, VT); 7643 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 7644 if (I < J) 7645 Tmp2 = 7646 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 7647 else 7648 Tmp2 = 7649 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 7650 7651 APInt Shift(Sz, 1); 7652 Shift <<= J; 7653 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 7654 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 7655 } 7656 7657 return Tmp; 7658 } 7659 7660 std::pair<SDValue, SDValue> 7661 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 7662 SelectionDAG &DAG) const { 7663 SDLoc SL(LD); 7664 SDValue Chain = LD->getChain(); 7665 SDValue BasePTR = LD->getBasePtr(); 7666 EVT SrcVT = LD->getMemoryVT(); 7667 EVT DstVT = LD->getValueType(0); 7668 ISD::LoadExtType ExtType = LD->getExtensionType(); 7669 7670 if (SrcVT.isScalableVector()) 7671 report_fatal_error("Cannot scalarize scalable vector loads"); 7672 7673 unsigned NumElem = SrcVT.getVectorNumElements(); 7674 7675 EVT SrcEltVT = SrcVT.getScalarType(); 7676 EVT DstEltVT = DstVT.getScalarType(); 7677 7678 // A vector must always be stored in memory as-is, i.e. without any padding 7679 // between the elements, since various code depend on it, e.g. in the 7680 // handling of a bitcast of a vector type to int, which may be done with a 7681 // vector store followed by an integer load. A vector that does not have 7682 // elements that are byte-sized must therefore be stored as an integer 7683 // built out of the extracted vector elements. 7684 if (!SrcEltVT.isByteSized()) { 7685 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 7686 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 7687 7688 unsigned NumSrcBits = SrcVT.getSizeInBits(); 7689 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 7690 7691 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 7692 SDValue SrcEltBitMask = DAG.getConstant( 7693 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 7694 7695 // Load the whole vector and avoid masking off the top bits as it makes 7696 // the codegen worse. 7697 SDValue Load = 7698 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 7699 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 7700 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7701 7702 SmallVector<SDValue, 8> Vals; 7703 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7704 unsigned ShiftIntoIdx = 7705 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7706 SDValue ShiftAmount = 7707 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 7708 LoadVT, SL, /*LegalTypes=*/false); 7709 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 7710 SDValue Elt = 7711 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 7712 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 7713 7714 if (ExtType != ISD::NON_EXTLOAD) { 7715 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 7716 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 7717 } 7718 7719 Vals.push_back(Scalar); 7720 } 7721 7722 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7723 return std::make_pair(Value, Load.getValue(1)); 7724 } 7725 7726 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 7727 assert(SrcEltVT.isByteSized()); 7728 7729 SmallVector<SDValue, 8> Vals; 7730 SmallVector<SDValue, 8> LoadChains; 7731 7732 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7733 SDValue ScalarLoad = 7734 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 7735 LD->getPointerInfo().getWithOffset(Idx * Stride), 7736 SrcEltVT, LD->getOriginalAlign(), 7737 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7738 7739 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 7740 7741 Vals.push_back(ScalarLoad.getValue(0)); 7742 LoadChains.push_back(ScalarLoad.getValue(1)); 7743 } 7744 7745 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 7746 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7747 7748 return std::make_pair(Value, NewChain); 7749 } 7750 7751 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 7752 SelectionDAG &DAG) const { 7753 SDLoc SL(ST); 7754 7755 SDValue Chain = ST->getChain(); 7756 SDValue BasePtr = ST->getBasePtr(); 7757 SDValue Value = ST->getValue(); 7758 EVT StVT = ST->getMemoryVT(); 7759 7760 if (StVT.isScalableVector()) 7761 report_fatal_error("Cannot scalarize scalable vector stores"); 7762 7763 // The type of the data we want to save 7764 EVT RegVT = Value.getValueType(); 7765 EVT RegSclVT = RegVT.getScalarType(); 7766 7767 // The type of data as saved in memory. 7768 EVT MemSclVT = StVT.getScalarType(); 7769 7770 unsigned NumElem = StVT.getVectorNumElements(); 7771 7772 // A vector must always be stored in memory as-is, i.e. without any padding 7773 // between the elements, since various code depend on it, e.g. in the 7774 // handling of a bitcast of a vector type to int, which may be done with a 7775 // vector store followed by an integer load. A vector that does not have 7776 // elements that are byte-sized must therefore be stored as an integer 7777 // built out of the extracted vector elements. 7778 if (!MemSclVT.isByteSized()) { 7779 unsigned NumBits = StVT.getSizeInBits(); 7780 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 7781 7782 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 7783 7784 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7785 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7786 DAG.getVectorIdxConstant(Idx, SL)); 7787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 7788 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 7789 unsigned ShiftIntoIdx = 7790 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7791 SDValue ShiftAmount = 7792 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 7793 SDValue ShiftedElt = 7794 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 7795 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 7796 } 7797 7798 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 7799 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7800 ST->getAAInfo()); 7801 } 7802 7803 // Store Stride in bytes 7804 unsigned Stride = MemSclVT.getSizeInBits() / 8; 7805 assert(Stride && "Zero stride!"); 7806 // Extract each of the elements from the original vector and save them into 7807 // memory individually. 7808 SmallVector<SDValue, 8> Stores; 7809 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7810 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7811 DAG.getVectorIdxConstant(Idx, SL)); 7812 7813 SDValue Ptr = 7814 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 7815 7816 // This scalar TruncStore may be illegal, but we legalize it later. 7817 SDValue Store = DAG.getTruncStore( 7818 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 7819 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7820 ST->getAAInfo()); 7821 7822 Stores.push_back(Store); 7823 } 7824 7825 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 7826 } 7827 7828 std::pair<SDValue, SDValue> 7829 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 7830 assert(LD->getAddressingMode() == ISD::UNINDEXED && 7831 "unaligned indexed loads not implemented!"); 7832 SDValue Chain = LD->getChain(); 7833 SDValue Ptr = LD->getBasePtr(); 7834 EVT VT = LD->getValueType(0); 7835 EVT LoadedVT = LD->getMemoryVT(); 7836 SDLoc dl(LD); 7837 auto &MF = DAG.getMachineFunction(); 7838 7839 if (VT.isFloatingPoint() || VT.isVector()) { 7840 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 7841 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 7842 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 7843 LoadedVT.isVector()) { 7844 // Scalarize the load and let the individual components be handled. 7845 return scalarizeVectorLoad(LD, DAG); 7846 } 7847 7848 // Expand to a (misaligned) integer load of the same size, 7849 // then bitconvert to floating point or vector. 7850 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 7851 LD->getMemOperand()); 7852 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 7853 if (LoadedVT != VT) 7854 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 7855 ISD::ANY_EXTEND, dl, VT, Result); 7856 7857 return std::make_pair(Result, newLoad.getValue(1)); 7858 } 7859 7860 // Copy the value to a (aligned) stack slot using (unaligned) integer 7861 // loads and stores, then do a (aligned) load from the stack slot. 7862 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 7863 unsigned LoadedBytes = LoadedVT.getStoreSize(); 7864 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7865 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 7866 7867 // Make sure the stack slot is also aligned for the register type. 7868 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 7869 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 7870 SmallVector<SDValue, 8> Stores; 7871 SDValue StackPtr = StackBase; 7872 unsigned Offset = 0; 7873 7874 EVT PtrVT = Ptr.getValueType(); 7875 EVT StackPtrVT = StackPtr.getValueType(); 7876 7877 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7878 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7879 7880 // Do all but one copies using the full register width. 7881 for (unsigned i = 1; i < NumRegs; i++) { 7882 // Load one integer register's worth from the original location. 7883 SDValue Load = DAG.getLoad( 7884 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 7885 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7886 LD->getAAInfo()); 7887 // Follow the load with a store to the stack slot. Remember the store. 7888 Stores.push_back(DAG.getStore( 7889 Load.getValue(1), dl, Load, StackPtr, 7890 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 7891 // Increment the pointers. 7892 Offset += RegBytes; 7893 7894 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7895 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7896 } 7897 7898 // The last copy may be partial. Do an extending load. 7899 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 7900 8 * (LoadedBytes - Offset)); 7901 SDValue Load = 7902 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 7903 LD->getPointerInfo().getWithOffset(Offset), MemVT, 7904 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7905 LD->getAAInfo()); 7906 // Follow the load with a store to the stack slot. Remember the store. 7907 // On big-endian machines this requires a truncating store to ensure 7908 // that the bits end up in the right place. 7909 Stores.push_back(DAG.getTruncStore( 7910 Load.getValue(1), dl, Load, StackPtr, 7911 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 7912 7913 // The order of the stores doesn't matter - say it with a TokenFactor. 7914 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7915 7916 // Finally, perform the original load only redirected to the stack slot. 7917 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 7918 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 7919 LoadedVT); 7920 7921 // Callers expect a MERGE_VALUES node. 7922 return std::make_pair(Load, TF); 7923 } 7924 7925 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 7926 "Unaligned load of unsupported type."); 7927 7928 // Compute the new VT that is half the size of the old one. This is an 7929 // integer MVT. 7930 unsigned NumBits = LoadedVT.getSizeInBits(); 7931 EVT NewLoadedVT; 7932 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 7933 NumBits >>= 1; 7934 7935 Align Alignment = LD->getOriginalAlign(); 7936 unsigned IncrementSize = NumBits / 8; 7937 ISD::LoadExtType HiExtType = LD->getExtensionType(); 7938 7939 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 7940 if (HiExtType == ISD::NON_EXTLOAD) 7941 HiExtType = ISD::ZEXTLOAD; 7942 7943 // Load the value in two parts 7944 SDValue Lo, Hi; 7945 if (DAG.getDataLayout().isLittleEndian()) { 7946 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7947 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7948 LD->getAAInfo()); 7949 7950 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7951 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 7952 LD->getPointerInfo().getWithOffset(IncrementSize), 7953 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7954 LD->getAAInfo()); 7955 } else { 7956 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7957 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7958 LD->getAAInfo()); 7959 7960 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7961 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 7962 LD->getPointerInfo().getWithOffset(IncrementSize), 7963 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7964 LD->getAAInfo()); 7965 } 7966 7967 // aggregate the two parts 7968 SDValue ShiftAmount = 7969 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 7970 DAG.getDataLayout())); 7971 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 7972 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 7973 7974 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 7975 Hi.getValue(1)); 7976 7977 return std::make_pair(Result, TF); 7978 } 7979 7980 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 7981 SelectionDAG &DAG) const { 7982 assert(ST->getAddressingMode() == ISD::UNINDEXED && 7983 "unaligned indexed stores not implemented!"); 7984 SDValue Chain = ST->getChain(); 7985 SDValue Ptr = ST->getBasePtr(); 7986 SDValue Val = ST->getValue(); 7987 EVT VT = Val.getValueType(); 7988 Align Alignment = ST->getOriginalAlign(); 7989 auto &MF = DAG.getMachineFunction(); 7990 EVT StoreMemVT = ST->getMemoryVT(); 7991 7992 SDLoc dl(ST); 7993 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 7994 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7995 if (isTypeLegal(intVT)) { 7996 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 7997 StoreMemVT.isVector()) { 7998 // Scalarize the store and let the individual components be handled. 7999 SDValue Result = scalarizeVectorStore(ST, DAG); 8000 return Result; 8001 } 8002 // Expand to a bitconvert of the value to the integer type of the 8003 // same size, then a (misaligned) int store. 8004 // FIXME: Does not handle truncating floating point stores! 8005 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8006 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8007 Alignment, ST->getMemOperand()->getFlags()); 8008 return Result; 8009 } 8010 // Do a (aligned) store to a stack slot, then copy from the stack slot 8011 // to the final destination using (unaligned) integer loads and stores. 8012 MVT RegVT = getRegisterType( 8013 *DAG.getContext(), 8014 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8015 EVT PtrVT = Ptr.getValueType(); 8016 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8017 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8018 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8019 8020 // Make sure the stack slot is also aligned for the register type. 8021 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8022 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8023 8024 // Perform the original store, only redirected to the stack slot. 8025 SDValue Store = DAG.getTruncStore( 8026 Chain, dl, Val, StackPtr, 8027 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8028 8029 EVT StackPtrVT = StackPtr.getValueType(); 8030 8031 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8032 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8033 SmallVector<SDValue, 8> Stores; 8034 unsigned Offset = 0; 8035 8036 // Do all but one copies using the full register width. 8037 for (unsigned i = 1; i < NumRegs; i++) { 8038 // Load one integer register's worth from the stack slot. 8039 SDValue Load = DAG.getLoad( 8040 RegVT, dl, Store, StackPtr, 8041 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8042 // Store it to the final location. Remember the store. 8043 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8044 ST->getPointerInfo().getWithOffset(Offset), 8045 ST->getOriginalAlign(), 8046 ST->getMemOperand()->getFlags())); 8047 // Increment the pointers. 8048 Offset += RegBytes; 8049 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8050 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8051 } 8052 8053 // The last store may be partial. Do a truncating store. On big-endian 8054 // machines this requires an extending load from the stack slot to ensure 8055 // that the bits are in the right place. 8056 EVT LoadMemVT = 8057 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8058 8059 // Load from the stack slot. 8060 SDValue Load = DAG.getExtLoad( 8061 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8062 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8063 8064 Stores.push_back( 8065 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8066 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8067 ST->getOriginalAlign(), 8068 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8069 // The order of the stores doesn't matter - say it with a TokenFactor. 8070 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8071 return Result; 8072 } 8073 8074 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8075 "Unaligned store of unknown type."); 8076 // Get the half-size VT 8077 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8078 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8079 unsigned IncrementSize = NumBits / 8; 8080 8081 // Divide the stored value in two parts. 8082 SDValue ShiftAmount = DAG.getConstant( 8083 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8084 SDValue Lo = Val; 8085 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8086 8087 // Store the two parts 8088 SDValue Store1, Store2; 8089 Store1 = DAG.getTruncStore(Chain, dl, 8090 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8091 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8092 ST->getMemOperand()->getFlags()); 8093 8094 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8095 Store2 = DAG.getTruncStore( 8096 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8097 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8098 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8099 8100 SDValue Result = 8101 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8102 return Result; 8103 } 8104 8105 SDValue 8106 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8107 const SDLoc &DL, EVT DataVT, 8108 SelectionDAG &DAG, 8109 bool IsCompressedMemory) const { 8110 SDValue Increment; 8111 EVT AddrVT = Addr.getValueType(); 8112 EVT MaskVT = Mask.getValueType(); 8113 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8114 "Incompatible types of Data and Mask"); 8115 if (IsCompressedMemory) { 8116 if (DataVT.isScalableVector()) 8117 report_fatal_error( 8118 "Cannot currently handle compressed memory with scalable vectors"); 8119 // Incrementing the pointer according to number of '1's in the mask. 8120 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8121 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8122 if (MaskIntVT.getSizeInBits() < 32) { 8123 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8124 MaskIntVT = MVT::i32; 8125 } 8126 8127 // Count '1's with POPCNT. 8128 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8129 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8130 // Scale is an element size in bytes. 8131 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8132 AddrVT); 8133 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8134 } else if (DataVT.isScalableVector()) { 8135 Increment = DAG.getVScale(DL, AddrVT, 8136 APInt(AddrVT.getFixedSizeInBits(), 8137 DataVT.getStoreSize().getKnownMinSize())); 8138 } else 8139 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8140 8141 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8142 } 8143 8144 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8145 EVT VecVT, const SDLoc &dl, 8146 ElementCount SubEC) { 8147 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8148 "Cannot index a scalable vector within a fixed-width vector"); 8149 8150 unsigned NElts = VecVT.getVectorMinNumElements(); 8151 unsigned NumSubElts = SubEC.getKnownMinValue(); 8152 EVT IdxVT = Idx.getValueType(); 8153 8154 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8155 // If this is a constant index and we know the value plus the number of the 8156 // elements in the subvector minus one is less than the minimum number of 8157 // elements then it's safe to return Idx. 8158 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8159 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8160 return Idx; 8161 SDValue VS = 8162 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8163 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8164 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8165 DAG.getConstant(NumSubElts, dl, IdxVT)); 8166 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8167 } 8168 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8169 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8170 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8171 DAG.getConstant(Imm, dl, IdxVT)); 8172 } 8173 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8174 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8175 DAG.getConstant(MaxIndex, dl, IdxVT)); 8176 } 8177 8178 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8179 SDValue VecPtr, EVT VecVT, 8180 SDValue Index) const { 8181 return getVectorSubVecPointer( 8182 DAG, VecPtr, VecVT, 8183 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8184 Index); 8185 } 8186 8187 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8188 SDValue VecPtr, EVT VecVT, 8189 EVT SubVecVT, 8190 SDValue Index) const { 8191 SDLoc dl(Index); 8192 // Make sure the index type is big enough to compute in. 8193 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8194 8195 EVT EltVT = VecVT.getVectorElementType(); 8196 8197 // Calculate the element offset and add it to the pointer. 8198 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8199 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8200 "Converting bits to bytes lost precision"); 8201 assert(SubVecVT.getVectorElementType() == EltVT && 8202 "Sub-vector must be a vector with matching element type"); 8203 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8204 SubVecVT.getVectorElementCount()); 8205 8206 EVT IdxVT = Index.getValueType(); 8207 if (SubVecVT.isScalableVector()) 8208 Index = 8209 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8210 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8211 8212 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8213 DAG.getConstant(EltSize, dl, IdxVT)); 8214 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8215 } 8216 8217 //===----------------------------------------------------------------------===// 8218 // Implementation of Emulated TLS Model 8219 //===----------------------------------------------------------------------===// 8220 8221 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8222 SelectionDAG &DAG) const { 8223 // Access to address of TLS varialbe xyz is lowered to a function call: 8224 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8225 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8226 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8227 SDLoc dl(GA); 8228 8229 ArgListTy Args; 8230 ArgListEntry Entry; 8231 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8232 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8233 StringRef EmuTlsVarName(NameString); 8234 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8235 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8236 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8237 Entry.Ty = VoidPtrType; 8238 Args.push_back(Entry); 8239 8240 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8241 8242 TargetLowering::CallLoweringInfo CLI(DAG); 8243 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8244 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8245 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8246 8247 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8248 // At last for X86 targets, maybe good for other targets too? 8249 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8250 MFI.setAdjustsStack(true); // Is this only for X86 target? 8251 MFI.setHasCalls(true); 8252 8253 assert((GA->getOffset() == 0) && 8254 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8255 return CallResult.first; 8256 } 8257 8258 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8259 SelectionDAG &DAG) const { 8260 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8261 if (!isCtlzFast()) 8262 return SDValue(); 8263 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8264 SDLoc dl(Op); 8265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8266 if (C->isZero() && CC == ISD::SETEQ) { 8267 EVT VT = Op.getOperand(0).getValueType(); 8268 SDValue Zext = Op.getOperand(0); 8269 if (VT.bitsLT(MVT::i32)) { 8270 VT = MVT::i32; 8271 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8272 } 8273 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8274 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8275 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8276 DAG.getConstant(Log2b, dl, MVT::i32)); 8277 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8278 } 8279 } 8280 return SDValue(); 8281 } 8282 8283 // Convert redundant addressing modes (e.g. scaling is redundant 8284 // when accessing bytes). 8285 ISD::MemIndexType 8286 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT, 8287 SDValue Offsets) const { 8288 bool IsScaledIndex = 8289 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED); 8290 bool IsSignedIndex = 8291 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED); 8292 8293 // Scaling is unimportant for bytes, canonicalize to unscaled. 8294 if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) 8295 return IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED; 8296 8297 return IndexType; 8298 } 8299 8300 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8301 SDValue Op0 = Node->getOperand(0); 8302 SDValue Op1 = Node->getOperand(1); 8303 EVT VT = Op0.getValueType(); 8304 unsigned Opcode = Node->getOpcode(); 8305 SDLoc DL(Node); 8306 8307 // umin(x,y) -> sub(x,usubsat(x,y)) 8308 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8309 isOperationLegal(ISD::USUBSAT, VT)) { 8310 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8311 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8312 } 8313 8314 // umax(x,y) -> add(x,usubsat(y,x)) 8315 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8316 isOperationLegal(ISD::USUBSAT, VT)) { 8317 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8318 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8319 } 8320 8321 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8322 ISD::CondCode CC; 8323 switch (Opcode) { 8324 default: llvm_unreachable("How did we get here?"); 8325 case ISD::SMAX: CC = ISD::SETGT; break; 8326 case ISD::SMIN: CC = ISD::SETLT; break; 8327 case ISD::UMAX: CC = ISD::SETUGT; break; 8328 case ISD::UMIN: CC = ISD::SETULT; break; 8329 } 8330 8331 // FIXME: Should really try to split the vector in case it's legal on a 8332 // subvector. 8333 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8334 return DAG.UnrollVectorOp(Node); 8335 8336 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8337 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8338 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8339 } 8340 8341 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8342 unsigned Opcode = Node->getOpcode(); 8343 SDValue LHS = Node->getOperand(0); 8344 SDValue RHS = Node->getOperand(1); 8345 EVT VT = LHS.getValueType(); 8346 SDLoc dl(Node); 8347 8348 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8349 assert(VT.isInteger() && "Expected operands to be integers"); 8350 8351 // usub.sat(a, b) -> umax(a, b) - b 8352 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8353 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8354 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8355 } 8356 8357 // uadd.sat(a, b) -> umin(a, ~b) + b 8358 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8359 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8360 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8361 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8362 } 8363 8364 unsigned OverflowOp; 8365 switch (Opcode) { 8366 case ISD::SADDSAT: 8367 OverflowOp = ISD::SADDO; 8368 break; 8369 case ISD::UADDSAT: 8370 OverflowOp = ISD::UADDO; 8371 break; 8372 case ISD::SSUBSAT: 8373 OverflowOp = ISD::SSUBO; 8374 break; 8375 case ISD::USUBSAT: 8376 OverflowOp = ISD::USUBO; 8377 break; 8378 default: 8379 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8380 "addition or subtraction node."); 8381 } 8382 8383 // FIXME: Should really try to split the vector in case it's legal on a 8384 // subvector. 8385 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8386 return DAG.UnrollVectorOp(Node); 8387 8388 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8389 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8390 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8391 SDValue SumDiff = Result.getValue(0); 8392 SDValue Overflow = Result.getValue(1); 8393 SDValue Zero = DAG.getConstant(0, dl, VT); 8394 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8395 8396 if (Opcode == ISD::UADDSAT) { 8397 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8398 // (LHS + RHS) | OverflowMask 8399 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8400 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8401 } 8402 // Overflow ? 0xffff.... : (LHS + RHS) 8403 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8404 } 8405 8406 if (Opcode == ISD::USUBSAT) { 8407 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8408 // (LHS - RHS) & ~OverflowMask 8409 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8410 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8411 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8412 } 8413 // Overflow ? 0 : (LHS - RHS) 8414 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8415 } 8416 8417 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8418 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8419 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8420 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8421 DAG.getConstant(BitWidth - 1, dl, VT)); 8422 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8423 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8424 } 8425 8426 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8427 unsigned Opcode = Node->getOpcode(); 8428 bool IsSigned = Opcode == ISD::SSHLSAT; 8429 SDValue LHS = Node->getOperand(0); 8430 SDValue RHS = Node->getOperand(1); 8431 EVT VT = LHS.getValueType(); 8432 SDLoc dl(Node); 8433 8434 assert((Node->getOpcode() == ISD::SSHLSAT || 8435 Node->getOpcode() == ISD::USHLSAT) && 8436 "Expected a SHLSAT opcode"); 8437 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8438 assert(VT.isInteger() && "Expected operands to be integers"); 8439 8440 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8441 8442 unsigned BW = VT.getScalarSizeInBits(); 8443 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8444 SDValue Orig = 8445 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8446 8447 SDValue SatVal; 8448 if (IsSigned) { 8449 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8450 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8451 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8452 SatMin, SatMax, ISD::SETLT); 8453 } else { 8454 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8455 } 8456 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8457 8458 return Result; 8459 } 8460 8461 SDValue 8462 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8463 assert((Node->getOpcode() == ISD::SMULFIX || 8464 Node->getOpcode() == ISD::UMULFIX || 8465 Node->getOpcode() == ISD::SMULFIXSAT || 8466 Node->getOpcode() == ISD::UMULFIXSAT) && 8467 "Expected a fixed point multiplication opcode"); 8468 8469 SDLoc dl(Node); 8470 SDValue LHS = Node->getOperand(0); 8471 SDValue RHS = Node->getOperand(1); 8472 EVT VT = LHS.getValueType(); 8473 unsigned Scale = Node->getConstantOperandVal(2); 8474 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8475 Node->getOpcode() == ISD::UMULFIXSAT); 8476 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8477 Node->getOpcode() == ISD::SMULFIXSAT); 8478 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8479 unsigned VTSize = VT.getScalarSizeInBits(); 8480 8481 if (!Scale) { 8482 // [us]mul.fix(a, b, 0) -> mul(a, b) 8483 if (!Saturating) { 8484 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8485 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8486 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8487 SDValue Result = 8488 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8489 SDValue Product = Result.getValue(0); 8490 SDValue Overflow = Result.getValue(1); 8491 SDValue Zero = DAG.getConstant(0, dl, VT); 8492 8493 APInt MinVal = APInt::getSignedMinValue(VTSize); 8494 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8495 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8496 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8497 // Xor the inputs, if resulting sign bit is 0 the product will be 8498 // positive, else negative. 8499 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8500 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8501 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8502 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8503 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8504 SDValue Result = 8505 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8506 SDValue Product = Result.getValue(0); 8507 SDValue Overflow = Result.getValue(1); 8508 8509 APInt MaxVal = APInt::getMaxValue(VTSize); 8510 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8511 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8512 } 8513 } 8514 8515 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8516 "Expected scale to be less than the number of bits if signed or at " 8517 "most the number of bits if unsigned."); 8518 assert(LHS.getValueType() == RHS.getValueType() && 8519 "Expected both operands to be the same type"); 8520 8521 // Get the upper and lower bits of the result. 8522 SDValue Lo, Hi; 8523 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8524 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8525 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8526 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8527 Lo = Result.getValue(0); 8528 Hi = Result.getValue(1); 8529 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8530 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8531 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8532 } else if (VT.isVector()) { 8533 return SDValue(); 8534 } else { 8535 report_fatal_error("Unable to expand fixed point multiplication."); 8536 } 8537 8538 if (Scale == VTSize) 8539 // Result is just the top half since we'd be shifting by the width of the 8540 // operand. Overflow impossible so this works for both UMULFIX and 8541 // UMULFIXSAT. 8542 return Hi; 8543 8544 // The result will need to be shifted right by the scale since both operands 8545 // are scaled. The result is given to us in 2 halves, so we only want part of 8546 // both in the result. 8547 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8548 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8549 DAG.getConstant(Scale, dl, ShiftTy)); 8550 if (!Saturating) 8551 return Result; 8552 8553 if (!Signed) { 8554 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8555 // widened multiplication) aren't all zeroes. 8556 8557 // Saturate to max if ((Hi >> Scale) != 0), 8558 // which is the same as if (Hi > ((1 << Scale) - 1)) 8559 APInt MaxVal = APInt::getMaxValue(VTSize); 8560 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8561 dl, VT); 8562 Result = DAG.getSelectCC(dl, Hi, LowMask, 8563 DAG.getConstant(MaxVal, dl, VT), Result, 8564 ISD::SETUGT); 8565 8566 return Result; 8567 } 8568 8569 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8570 // widened multiplication) aren't all ones or all zeroes. 8571 8572 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8573 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8574 8575 if (Scale == 0) { 8576 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8577 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8578 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8579 // Saturated to SatMin if wide product is negative, and SatMax if wide 8580 // product is positive ... 8581 SDValue Zero = DAG.getConstant(0, dl, VT); 8582 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8583 ISD::SETLT); 8584 // ... but only if we overflowed. 8585 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 8586 } 8587 8588 // We handled Scale==0 above so all the bits to examine is in Hi. 8589 8590 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 8591 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 8592 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 8593 dl, VT); 8594 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 8595 // Saturate to min if (Hi >> (Scale - 1)) < -1), 8596 // which is the same as if (HI < (-1 << (Scale - 1)) 8597 SDValue HighMask = 8598 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 8599 dl, VT); 8600 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 8601 return Result; 8602 } 8603 8604 SDValue 8605 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 8606 SDValue LHS, SDValue RHS, 8607 unsigned Scale, SelectionDAG &DAG) const { 8608 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 8609 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 8610 "Expected a fixed point division opcode"); 8611 8612 EVT VT = LHS.getValueType(); 8613 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 8614 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 8615 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8616 8617 // If there is enough room in the type to upscale the LHS or downscale the 8618 // RHS before the division, we can perform it in this type without having to 8619 // resize. For signed operations, the LHS headroom is the number of 8620 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8621 // The headroom for the RHS is the number of trailing zeroes. 8622 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8623 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8624 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 8625 8626 // For signed saturating operations, we need to be able to detect true integer 8627 // division overflow; that is, when you have MIN / -EPS. However, this 8628 // is undefined behavior and if we emit divisions that could take such 8629 // values it may cause undesired behavior (arithmetic exceptions on x86, for 8630 // example). 8631 // Avoid this by requiring an extra bit so that we never get this case. 8632 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 8633 // signed saturating division, we need to emit a whopping 32-bit division. 8634 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 8635 return SDValue(); 8636 8637 unsigned LHSShift = std::min(LHSLead, Scale); 8638 unsigned RHSShift = Scale - LHSShift; 8639 8640 // At this point, we know that if we shift the LHS up by LHSShift and the 8641 // RHS down by RHSShift, we can emit a regular division with a final scaling 8642 // factor of Scale. 8643 8644 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8645 if (LHSShift) 8646 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 8647 DAG.getConstant(LHSShift, dl, ShiftTy)); 8648 if (RHSShift) 8649 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 8650 DAG.getConstant(RHSShift, dl, ShiftTy)); 8651 8652 SDValue Quot; 8653 if (Signed) { 8654 // For signed operations, if the resulting quotient is negative and the 8655 // remainder is nonzero, subtract 1 from the quotient to round towards 8656 // negative infinity. 8657 SDValue Rem; 8658 // FIXME: Ideally we would always produce an SDIVREM here, but if the 8659 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 8660 // we couldn't just form a libcall, but the type legalizer doesn't do it. 8661 if (isTypeLegal(VT) && 8662 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 8663 Quot = DAG.getNode(ISD::SDIVREM, dl, 8664 DAG.getVTList(VT, VT), 8665 LHS, RHS); 8666 Rem = Quot.getValue(1); 8667 Quot = Quot.getValue(0); 8668 } else { 8669 Quot = DAG.getNode(ISD::SDIV, dl, VT, 8670 LHS, RHS); 8671 Rem = DAG.getNode(ISD::SREM, dl, VT, 8672 LHS, RHS); 8673 } 8674 SDValue Zero = DAG.getConstant(0, dl, VT); 8675 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 8676 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 8677 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 8678 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 8679 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 8680 DAG.getConstant(1, dl, VT)); 8681 Quot = DAG.getSelect(dl, VT, 8682 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 8683 Sub1, Quot); 8684 } else 8685 Quot = DAG.getNode(ISD::UDIV, dl, VT, 8686 LHS, RHS); 8687 8688 return Quot; 8689 } 8690 8691 void TargetLowering::expandUADDSUBO( 8692 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8693 SDLoc dl(Node); 8694 SDValue LHS = Node->getOperand(0); 8695 SDValue RHS = Node->getOperand(1); 8696 bool IsAdd = Node->getOpcode() == ISD::UADDO; 8697 8698 // If ADD/SUBCARRY is legal, use that instead. 8699 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 8700 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 8701 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 8702 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 8703 { LHS, RHS, CarryIn }); 8704 Result = SDValue(NodeCarry.getNode(), 0); 8705 Overflow = SDValue(NodeCarry.getNode(), 1); 8706 return; 8707 } 8708 8709 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8710 LHS.getValueType(), LHS, RHS); 8711 8712 EVT ResultType = Node->getValueType(1); 8713 EVT SetCCType = getSetCCResultType( 8714 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8715 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 8716 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 8717 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8718 } 8719 8720 void TargetLowering::expandSADDSUBO( 8721 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8722 SDLoc dl(Node); 8723 SDValue LHS = Node->getOperand(0); 8724 SDValue RHS = Node->getOperand(1); 8725 bool IsAdd = Node->getOpcode() == ISD::SADDO; 8726 8727 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8728 LHS.getValueType(), LHS, RHS); 8729 8730 EVT ResultType = Node->getValueType(1); 8731 EVT OType = getSetCCResultType( 8732 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8733 8734 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 8735 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 8736 if (isOperationLegal(OpcSat, LHS.getValueType())) { 8737 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 8738 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 8739 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8740 return; 8741 } 8742 8743 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 8744 8745 // For an addition, the result should be less than one of the operands (LHS) 8746 // if and only if the other operand (RHS) is negative, otherwise there will 8747 // be overflow. 8748 // For a subtraction, the result should be less than one of the operands 8749 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 8750 // otherwise there will be overflow. 8751 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 8752 SDValue ConditionRHS = 8753 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 8754 8755 Overflow = DAG.getBoolExtOrTrunc( 8756 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 8757 ResultType, ResultType); 8758 } 8759 8760 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 8761 SDValue &Overflow, SelectionDAG &DAG) const { 8762 SDLoc dl(Node); 8763 EVT VT = Node->getValueType(0); 8764 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8765 SDValue LHS = Node->getOperand(0); 8766 SDValue RHS = Node->getOperand(1); 8767 bool isSigned = Node->getOpcode() == ISD::SMULO; 8768 8769 // For power-of-two multiplications we can use a simpler shift expansion. 8770 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 8771 const APInt &C = RHSC->getAPIntValue(); 8772 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 8773 if (C.isPowerOf2()) { 8774 // smulo(x, signed_min) is same as umulo(x, signed_min). 8775 bool UseArithShift = isSigned && !C.isMinSignedValue(); 8776 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8777 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 8778 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 8779 Overflow = DAG.getSetCC(dl, SetCCVT, 8780 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 8781 dl, VT, Result, ShiftAmt), 8782 LHS, ISD::SETNE); 8783 return true; 8784 } 8785 } 8786 8787 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 8788 if (VT.isVector()) 8789 WideVT = 8790 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 8791 8792 SDValue BottomHalf; 8793 SDValue TopHalf; 8794 static const unsigned Ops[2][3] = 8795 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 8796 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 8797 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 8798 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8799 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 8800 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 8801 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 8802 RHS); 8803 TopHalf = BottomHalf.getValue(1); 8804 } else if (isTypeLegal(WideVT)) { 8805 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 8806 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 8807 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 8808 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 8809 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 8810 getShiftAmountTy(WideVT, DAG.getDataLayout())); 8811 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 8812 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 8813 } else { 8814 if (VT.isVector()) 8815 return false; 8816 8817 // We can fall back to a libcall with an illegal type for the MUL if we 8818 // have a libcall big enough. 8819 // Also, we can fall back to a division in some cases, but that's a big 8820 // performance hit in the general case. 8821 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 8822 if (WideVT == MVT::i16) 8823 LC = RTLIB::MUL_I16; 8824 else if (WideVT == MVT::i32) 8825 LC = RTLIB::MUL_I32; 8826 else if (WideVT == MVT::i64) 8827 LC = RTLIB::MUL_I64; 8828 else if (WideVT == MVT::i128) 8829 LC = RTLIB::MUL_I128; 8830 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 8831 8832 SDValue HiLHS; 8833 SDValue HiRHS; 8834 if (isSigned) { 8835 // The high part is obtained by SRA'ing all but one of the bits of low 8836 // part. 8837 unsigned LoSize = VT.getFixedSizeInBits(); 8838 HiLHS = 8839 DAG.getNode(ISD::SRA, dl, VT, LHS, 8840 DAG.getConstant(LoSize - 1, dl, 8841 getPointerTy(DAG.getDataLayout()))); 8842 HiRHS = 8843 DAG.getNode(ISD::SRA, dl, VT, RHS, 8844 DAG.getConstant(LoSize - 1, dl, 8845 getPointerTy(DAG.getDataLayout()))); 8846 } else { 8847 HiLHS = DAG.getConstant(0, dl, VT); 8848 HiRHS = DAG.getConstant(0, dl, VT); 8849 } 8850 8851 // Here we're passing the 2 arguments explicitly as 4 arguments that are 8852 // pre-lowered to the correct types. This all depends upon WideVT not 8853 // being a legal type for the architecture and thus has to be split to 8854 // two arguments. 8855 SDValue Ret; 8856 TargetLowering::MakeLibCallOptions CallOptions; 8857 CallOptions.setSExt(isSigned); 8858 CallOptions.setIsPostTypeLegalization(true); 8859 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 8860 // Halves of WideVT are packed into registers in different order 8861 // depending on platform endianness. This is usually handled by 8862 // the C calling convention, but we can't defer to it in 8863 // the legalizer. 8864 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 8865 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8866 } else { 8867 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 8868 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8869 } 8870 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 8871 "Ret value is a collection of constituent nodes holding result."); 8872 if (DAG.getDataLayout().isLittleEndian()) { 8873 // Same as above. 8874 BottomHalf = Ret.getOperand(0); 8875 TopHalf = Ret.getOperand(1); 8876 } else { 8877 BottomHalf = Ret.getOperand(1); 8878 TopHalf = Ret.getOperand(0); 8879 } 8880 } 8881 8882 Result = BottomHalf; 8883 if (isSigned) { 8884 SDValue ShiftAmt = DAG.getConstant( 8885 VT.getScalarSizeInBits() - 1, dl, 8886 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 8887 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 8888 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 8889 } else { 8890 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 8891 DAG.getConstant(0, dl, VT), ISD::SETNE); 8892 } 8893 8894 // Truncate the result if SetCC returns a larger type than needed. 8895 EVT RType = Node->getValueType(1); 8896 if (RType.bitsLT(Overflow.getValueType())) 8897 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 8898 8899 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 8900 "Unexpected result type for S/UMULO legalization"); 8901 return true; 8902 } 8903 8904 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 8905 SDLoc dl(Node); 8906 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8907 SDValue Op = Node->getOperand(0); 8908 EVT VT = Op.getValueType(); 8909 8910 if (VT.isScalableVector()) 8911 report_fatal_error( 8912 "Expanding reductions for scalable vectors is undefined."); 8913 8914 // Try to use a shuffle reduction for power of two vectors. 8915 if (VT.isPow2VectorType()) { 8916 while (VT.getVectorNumElements() > 1) { 8917 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8918 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 8919 break; 8920 8921 SDValue Lo, Hi; 8922 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 8923 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 8924 VT = HalfVT; 8925 } 8926 } 8927 8928 EVT EltVT = VT.getVectorElementType(); 8929 unsigned NumElts = VT.getVectorNumElements(); 8930 8931 SmallVector<SDValue, 8> Ops; 8932 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 8933 8934 SDValue Res = Ops[0]; 8935 for (unsigned i = 1; i < NumElts; i++) 8936 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 8937 8938 // Result type may be wider than element type. 8939 if (EltVT != Node->getValueType(0)) 8940 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 8941 return Res; 8942 } 8943 8944 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 8945 SDLoc dl(Node); 8946 SDValue AccOp = Node->getOperand(0); 8947 SDValue VecOp = Node->getOperand(1); 8948 SDNodeFlags Flags = Node->getFlags(); 8949 8950 EVT VT = VecOp.getValueType(); 8951 EVT EltVT = VT.getVectorElementType(); 8952 8953 if (VT.isScalableVector()) 8954 report_fatal_error( 8955 "Expanding reductions for scalable vectors is undefined."); 8956 8957 unsigned NumElts = VT.getVectorNumElements(); 8958 8959 SmallVector<SDValue, 8> Ops; 8960 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 8961 8962 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8963 8964 SDValue Res = AccOp; 8965 for (unsigned i = 0; i < NumElts; i++) 8966 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 8967 8968 return Res; 8969 } 8970 8971 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 8972 SelectionDAG &DAG) const { 8973 EVT VT = Node->getValueType(0); 8974 SDLoc dl(Node); 8975 bool isSigned = Node->getOpcode() == ISD::SREM; 8976 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 8977 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 8978 SDValue Dividend = Node->getOperand(0); 8979 SDValue Divisor = Node->getOperand(1); 8980 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 8981 SDVTList VTs = DAG.getVTList(VT, VT); 8982 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 8983 return true; 8984 } 8985 if (isOperationLegalOrCustom(DivOpc, VT)) { 8986 // X % Y -> X-X/Y*Y 8987 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 8988 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 8989 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 8990 return true; 8991 } 8992 return false; 8993 } 8994 8995 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 8996 SelectionDAG &DAG) const { 8997 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 8998 SDLoc dl(SDValue(Node, 0)); 8999 SDValue Src = Node->getOperand(0); 9000 9001 // DstVT is the result type, while SatVT is the size to which we saturate 9002 EVT SrcVT = Src.getValueType(); 9003 EVT DstVT = Node->getValueType(0); 9004 9005 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9006 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9007 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9008 assert(SatWidth <= DstWidth && 9009 "Expected saturation width smaller than result width"); 9010 9011 // Determine minimum and maximum integer values and their corresponding 9012 // floating-point values. 9013 APInt MinInt, MaxInt; 9014 if (IsSigned) { 9015 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth); 9016 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth); 9017 } else { 9018 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth); 9019 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth); 9020 } 9021 9022 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9023 // libcall emission cannot handle this. Large result types will fail. 9024 if (SrcVT == MVT::f16) { 9025 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9026 SrcVT = Src.getValueType(); 9027 } 9028 9029 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9030 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9031 9032 APFloat::opStatus MinStatus = 9033 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9034 APFloat::opStatus MaxStatus = 9035 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9036 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9037 !(MaxStatus & APFloat::opStatus::opInexact); 9038 9039 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9040 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9041 9042 // If the integer bounds are exactly representable as floats and min/max are 9043 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9044 // of comparisons and selects. 9045 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9046 isOperationLegal(ISD::FMAXNUM, SrcVT); 9047 if (AreExactFloatBounds && MinMaxLegal) { 9048 SDValue Clamped = Src; 9049 9050 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9051 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9052 // Clamp by MaxFloat from above. NaN cannot occur. 9053 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9054 // Convert clamped value to integer. 9055 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9056 dl, DstVT, Clamped); 9057 9058 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9059 // which will cast to zero. 9060 if (!IsSigned) 9061 return FpToInt; 9062 9063 // Otherwise, select 0 if Src is NaN. 9064 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9065 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9066 ISD::CondCode::SETUO); 9067 } 9068 9069 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9070 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9071 9072 // Result of direct conversion. The assumption here is that the operation is 9073 // non-trapping and it's fine to apply it to an out-of-range value if we 9074 // select it away later. 9075 SDValue FpToInt = 9076 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9077 9078 SDValue Select = FpToInt; 9079 9080 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9081 // MinInt if Src is NaN. 9082 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9083 ISD::CondCode::SETULT); 9084 // If Src OGT MaxFloat, select MaxInt. 9085 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9086 ISD::CondCode::SETOGT); 9087 9088 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9089 // is already zero. 9090 if (!IsSigned) 9091 return Select; 9092 9093 // Otherwise, select 0 if Src is NaN. 9094 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9095 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9096 } 9097 9098 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9099 SelectionDAG &DAG) const { 9100 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9101 assert(Node->getValueType(0).isScalableVector() && 9102 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9103 9104 EVT VT = Node->getValueType(0); 9105 SDValue V1 = Node->getOperand(0); 9106 SDValue V2 = Node->getOperand(1); 9107 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9108 SDLoc DL(Node); 9109 9110 // Expand through memory thusly: 9111 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9112 // Store V1, Ptr 9113 // Store V2, Ptr + sizeof(V1) 9114 // If (Imm < 0) 9115 // TrailingElts = -Imm 9116 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9117 // else 9118 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9119 // Res = Load Ptr 9120 9121 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9122 9123 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9124 VT.getVectorElementCount() * 2); 9125 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9126 EVT PtrVT = StackPtr.getValueType(); 9127 auto &MF = DAG.getMachineFunction(); 9128 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9129 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9130 9131 // Store the lo part of CONCAT_VECTORS(V1, V2) 9132 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9133 // Store the hi part of CONCAT_VECTORS(V1, V2) 9134 SDValue OffsetToV2 = DAG.getVScale( 9135 DL, PtrVT, 9136 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9137 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9138 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9139 9140 if (Imm >= 0) { 9141 // Load back the required element. getVectorElementPointer takes care of 9142 // clamping the index if it's out-of-bounds. 9143 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9144 // Load the spliced result 9145 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9146 MachinePointerInfo::getUnknownStack(MF)); 9147 } 9148 9149 uint64_t TrailingElts = -Imm; 9150 9151 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9152 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9153 SDValue TrailingBytes = 9154 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9155 9156 if (TrailingElts > VT.getVectorMinNumElements()) { 9157 SDValue VLBytes = DAG.getVScale( 9158 DL, PtrVT, 9159 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9160 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9161 } 9162 9163 // Calculate the start address of the spliced result. 9164 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9165 9166 // Load the spliced result 9167 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9168 MachinePointerInfo::getUnknownStack(MF)); 9169 } 9170 9171 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9172 SDValue &LHS, SDValue &RHS, 9173 SDValue &CC, bool &NeedInvert, 9174 const SDLoc &dl, SDValue &Chain, 9175 bool IsSignaling) const { 9176 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9177 MVT OpVT = LHS.getSimpleValueType(); 9178 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9179 NeedInvert = false; 9180 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9181 default: 9182 llvm_unreachable("Unknown condition code action!"); 9183 case TargetLowering::Legal: 9184 // Nothing to do. 9185 break; 9186 case TargetLowering::Expand: { 9187 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9188 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9189 std::swap(LHS, RHS); 9190 CC = DAG.getCondCode(InvCC); 9191 return true; 9192 } 9193 // Swapping operands didn't work. Try inverting the condition. 9194 bool NeedSwap = false; 9195 InvCC = getSetCCInverse(CCCode, OpVT); 9196 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9197 // If inverting the condition is not enough, try swapping operands 9198 // on top of it. 9199 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9200 NeedSwap = true; 9201 } 9202 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9203 CC = DAG.getCondCode(InvCC); 9204 NeedInvert = true; 9205 if (NeedSwap) 9206 std::swap(LHS, RHS); 9207 return true; 9208 } 9209 9210 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9211 unsigned Opc = 0; 9212 switch (CCCode) { 9213 default: 9214 llvm_unreachable("Don't know how to expand this condition!"); 9215 case ISD::SETUO: 9216 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9217 CC1 = ISD::SETUNE; 9218 CC2 = ISD::SETUNE; 9219 Opc = ISD::OR; 9220 break; 9221 } 9222 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9223 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9224 NeedInvert = true; 9225 LLVM_FALLTHROUGH; 9226 case ISD::SETO: 9227 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9228 "If SETO is expanded, SETOEQ must be legal!"); 9229 CC1 = ISD::SETOEQ; 9230 CC2 = ISD::SETOEQ; 9231 Opc = ISD::AND; 9232 break; 9233 case ISD::SETONE: 9234 case ISD::SETUEQ: 9235 // If the SETUO or SETO CC isn't legal, we might be able to use 9236 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9237 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9238 // the operands. 9239 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9240 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9241 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9242 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9243 CC1 = ISD::SETOGT; 9244 CC2 = ISD::SETOLT; 9245 Opc = ISD::OR; 9246 NeedInvert = ((unsigned)CCCode & 0x8U); 9247 break; 9248 } 9249 LLVM_FALLTHROUGH; 9250 case ISD::SETOEQ: 9251 case ISD::SETOGT: 9252 case ISD::SETOGE: 9253 case ISD::SETOLT: 9254 case ISD::SETOLE: 9255 case ISD::SETUNE: 9256 case ISD::SETUGT: 9257 case ISD::SETUGE: 9258 case ISD::SETULT: 9259 case ISD::SETULE: 9260 // If we are floating point, assign and break, otherwise fall through. 9261 if (!OpVT.isInteger()) { 9262 // We can use the 4th bit to tell if we are the unordered 9263 // or ordered version of the opcode. 9264 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9265 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9266 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9267 break; 9268 } 9269 // Fallthrough if we are unsigned integer. 9270 LLVM_FALLTHROUGH; 9271 case ISD::SETLE: 9272 case ISD::SETGT: 9273 case ISD::SETGE: 9274 case ISD::SETLT: 9275 case ISD::SETNE: 9276 case ISD::SETEQ: 9277 // If all combinations of inverting the condition and swapping operands 9278 // didn't work then we have no means to expand the condition. 9279 llvm_unreachable("Don't know how to expand this condition!"); 9280 } 9281 9282 SDValue SetCC1, SetCC2; 9283 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9284 // If we aren't the ordered or unorder operation, 9285 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9286 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9287 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9288 } else { 9289 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9290 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9291 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9292 } 9293 if (Chain) 9294 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9295 SetCC2.getValue(1)); 9296 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9297 RHS = SDValue(); 9298 CC = SDValue(); 9299 return true; 9300 } 9301 } 9302 return false; 9303 } 9304