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