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