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