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