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